2011-11-01 141 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