我正在寻找一种方法,将var selectedId = []
中的.change(function{})
值传递给全局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
如果有人有想法解决这个问题,我将深表感谢。
谢谢!
凯文
答案 0 :(得分:0)
你可以这样做。
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;