簡體   English   中英

修改函數中的javascript變量

[英]modifying javascript variable within function

我已經閱讀了全局聲明變量,然后能夠在函數中修改它們,但事情對我來說並不奏效。

這是我的代碼:

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); 

這是因為只有在從select元素觸發change事件時才會執行change()處理程序。 您正在順序執行中使用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();

解決此問題的方法是從更改處理程序中執行需要選擇者值的代碼。 您不應該首先將它存儲在全局變量中。

// 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);

});

為了解釋,當select的值實際改變時,僅執行.change()回調函數。 它將在稍后的某個時間召喚。 因此,要在稍后的某個時間使用選擇者的值,您需要在更改新值的同時執行需要該值的代碼。

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

這是因為change處理程序是一個回調函數,它會在事件發生后觸發,而不是執行代碼順序

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

 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);
}

注意:觸發更改后,無法在新函數mynewfunc外部訪問變量selectee器。

演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM