這是因爲只有當更改事件從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();
您的代碼不起作用。只有在選擇控件的更改事件被觸發後,選擇者纔會反映新值。屆時,console.log(selectee)必須已執行。 – Chibuzo
定義「事情不起作用」。假設你在改變選擇的選項後獲得* selectee *的價值? – RobG
'$('select option:selected').val();'可以簡單地爲'this.value'。 – RobG