将.change函数中变量的值传递并更新到全局变量Jquery

Pass and update values from variable in .change function to global variable Jquery

本文关键字:更新 全局变量 Jquery 值传 函数 change 变量      更新时间:2023-09-26

我正在寻找一种方法,将值数组从.change(function{})中的var selectedId = []传递到全局var globalId = []。所以每次selectedId中的值发生变化时,我都希望有一个像selectedId.update(globalId)selectedId = globalId.update()这样的函数来更新全局id,但我不知道如何编写这部分。最终,我可以在其他更改功能中使用最新的globalId。这是我的代码

$(function(){
    var globalId = [];
    $("#listbox1").change(function(){
        var selectedId =[];
        //get each selection
        $.each(selectedId , function (fIndex, fValue) {
            $.each(this.options, function (value, option) {
                if (this.selected) {
                    selectedId.push(option.value);
                }
            });
        });
        // send value to globalId 
        selectedId = globalId; // how to keep globalId up-to-date 
        // for everytime selectedId changes
        $.ajax({
            //....
            traditional: true, 
            data:{"// id in the controller": selectedId},
            success{...},
            error{...}
        });//end ajax
    });//end listbox1 change
    $("#listbox2").change(function(){
        var selectedId2 = [];
        // same each function to get selected <option>s as listbox1
        $.each{...
            $each{...
            };
        };
        $.ajax({
            //...
            data:{
                "//id1 in the controller": selectedId2, 
                "//id2 in the controller": globalId 
            },// this is the reason why I want to pass those values from listbox1  
            //to globalId so that I can use these two arrays in my controller function
            success{...},  
            error{}              
        });
    })//end listbox2 change
});//end ready

如果有人有解决这个问题的想法,我将不胜感激。

谢谢!

Kevin

您可以这样做。

function GlobalIds(){
   var globalIds;
   return{
     getGlobalIds: function(){ return globalIds;},
     setGlobalIds: function(ids){ globalIds = ids}
    }
}
var globalIds = new GlobalIds();
globalIds.setGlobalIds([1,2]);
console.log(globalIds.getGlobalIds());
globalIds.setGlobalIds([3,4]);
console.log(globalIds.getGlobalIds());

而且,你们似乎做作业的方式不对。代替

// send value to globalId 
          selectedId = globalId; // how to keep globalId up-to-date 
                                // for everytime selectedId changes

应该是

 globalId = selectedId;