修改函数中的javascript变量

modifying javascript variable within function

本文关键字:javascript 变量 函数 修改      更新时间:2023-09-26

我读过关于全局声明变量,然后能够在函数中修改它们的文章,但事情对我来说并不顺利。

这是我的代码:

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()处理程序才会被执行。您在顺序执行中使用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);

如果您希望selecteeselect元素中选择值,那么您可以执行类似的操作

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

解决此问题的方法是从更改处理程序中执行需要selectedee值的代码。首先不应该将其存储在全局变量中。

// 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()回调函数仅在select的值实际更改时执行。它将在稍后的某个时候被调用。因此,为了稍后使用selectedee的值,您需要在更改新值的同时执行需要该值的代码。

您的代码并不像您想象的那样是过程性的。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

演示