2011-11-01 142 views
-2

如何查看回调函数中的参数“url”?获取回调函数中定义的参数值javascript函数

功能在全球范围内宣布:

var showPrompt = function(text, callBackFunc){ 
    $('#msg').html(text); 
    $('#msgbtn').click(function(){callBackFunc();}) 
}; 

//调用函数

$('li').click(function(){ // about 100 li el. 
    var url = '/prod/' + $(this).data('id'); 
    showPrompt('Page will be redirected', function(url){ 
     window.location = url; 
    }) 
}) 
+0

你为什么反对投票题? – jmav

回答

1
showPrompt = function(text, callBackFunc, args){ 
    $('#msg').html(text); 
    $('#msgbtn').click(function(){callBackFunc(args);}) 
}; 
//calling function 

$('li').click(function(){ // about 100 li el. 
    var url = '/prod/' + $(this).attr('id'); 
    showPrompt('Page will be redirected', function(args){ 
     alert(args.url); 
    }, {'url':url}) 
}) 

用这种方式(清洁方法)

“ - 或 -

showPrompt = function(text, callBackFunc){ 
    $('#msg').html(text); 
    $('#msgbtn').click(callBackFunc); 
}; 
//calling function 

$('li').click(function(){ // about 100 li el. 
    var url = '/prod/' + $(this).attr('id'); 
    showPrompt('Page will be redirected', function(){ 
     alert(url); 
    }) 
}) 
+0

但你仍然知道如何重用通过匿名函数url参数? – jmav

+0

我无法理解你的问题。 – hungryMind

1

不要声明url作为参数传递给你的函数,你会得到你想要的外url

var url = ('error.html'); 
showPrompt('Page will be redirected', function() { 
    window.location = url; 
}); 

而且你不需要额外的ano nymous函数内部showPrompt,只是这是好的:

showPrompt = function(text, callBackFunc) { 
    $('#msg').html(text); 
    $('#msgbtn').click(callBackFunc); 
}; 

除非当然,如果你想随时拨打callBackFunc不带任何参数。附加为

.click(callBackFunc) 

表示将以该事件为参数调用它。

+0

问题是,我想要传递url参数给showPrompt回调函数,我不想在全局命名空间中声明它。 – jmav

+0

@jmav:如果'showPrompt'调用在另一个函数内,那么'url'将是该函数的局部变量,但也会被闭包捕获;所以,没有全球需要。 –

+0

是真的:但是如果我使用按钮,用户稍后点击它会怎么样。代码不知道在哪个上下文中,所以它不知道url值。 – jmav

0
showPrompt = function(text, callBackFunc) { 
    var url = ('error.html'); 
    $('#msg').html(text); 
    $('#msgbtn').click(function(){callBackFunc(url);}) 
}; 

//calling function 
showPrompt('Page will be redirected', function(url){ 
    window.location = url; 
}) 

你可以这样做。刚刚宣布的URL中的函数调用callBackFunc关闭,然后将它作为参数传递

+0

因为我很伤心,我想将url参数传递给showPrompt回调函数 – jmav

+0

他的解决方案是传递一个url参数。我认为你需要详细说明你想要完成什么。 – erturne