2013-11-25 137 views
1

我已經閱讀過關於聲明全局變量然後能夠在函數中修改它們的問題,但事情並不適合我。在函數內修改javascript變量

這裏是我的代碼:

var selectee = "JK"; 
// get state selected 
$('select.form-control.bfh-states').change(function() { 
    selectee = $('select option:selected').val(); 
    // works correctly, but i need to access it outside the function 
    console.log(selectee); 
}); 

// output JK, should change based on a select box on the form 
console.log(selectee); 
+0

您的代碼不起作用。只有在選擇控件的更改事件被觸發後,選擇者纔會反映新值。屆時,console.log(selectee)必須已執行。 – Chibuzo

+0

定義「事情不起作用」。假設你在改變選擇的選項後獲得* selectee *的價值? – RobG

+0

'$('select option:selected').val();'可以簡單地爲'this.value'。 – RobG

回答

2

這是因爲只有當更改事件從select元素解僱的change()處理程序將得到執行。您正在使用的順序executio的console.log()聲明的變化處理被激發

//this is correct 
var selectee = "JK"; 

//this registers a change handler for the select element 
$('select.form-control.bfh-states').change(function() { 
    //but this will not execute now!!! it will get executed only when the select elements change event is fired 
    selectee = $(this).val(); 
    console.log(selectee); // works correctly, but i need to access it outside the function 
}); 

//this will get executed as soon as the change handler is registered not after the handler is executed 
console.log(selectee); 

之前,如果你想selectee有在select元素選擇,那麼你可以做這樣的事情

其價值將得到執行
var selectee = $('select.form-control.bfh-states').val() || "JK"; 

或手動觸發選擇更改處理,一旦處理程序安裝在DOM準備像

var selectee = "JK"; 

$('select.form-control.bfh-states').change(function() { 
    selectee = $(this).val(); 
    console.log(selectee); // works correctly, but i need to access it outside the function 
}).change(); 
+0

感謝這個作品太棒了! – compguy24

0

你的代碼不像你想象的那樣工作。 selectee只有在您的選擇控件的更改事件被觸發後纔會反映新值。事件處理程序中的代碼在被調用/觸發/觸發之前不會執行。但是那些外部的,比如你的console.log(selectee)將在第一次加載代碼時執行(在你的情況下,改變事件沒有被調用)。

0

這是因爲change處理程序是一個回調,事件發生後,它將解僱,不執行代碼順序

1

解決這個問題的方法是執行從內部需求徵召員的值的代碼改變處理器。你不應該把它存儲在一個全局變量中。

// get state selected 
$('select.form-control.bfh-states').change(function() { 
    var selectee = $('select option:selected').val(); 
    console.log(selectee); // works correctly, but i need to access it outside the function 

    // call your other code from here and pass it the current value of selectee 
    myOtherFunction(selectee); 

}); 

爲了解釋,當選擇的值實際上改變只執行.change()回調函數。它將在某個時候被調用。因此,爲了稍後使用selectee的值,您需要在新值更改的同時執行需要該值的代碼。

0

另一種方法是將選定的值傳遞給一個新的函數,從而在該函數內(不是全局的)訪問它。試試這個:

selectee = "JK"; 
// get state selected 
$('select.form-control.bfh-states').change(function() { 

selectee = $('select option:selected').val(); 
// works correctly, but i need to access it outside the function 
mynewfunc(selectee); 

}); 
function mynewfunc(){ 
alert(selectee); 
} 

注:變量selectee一旦變化被觸發並不之外的新功能mynewfunc訪問。

Demo