选择时的 Javascript 动态 onChange 事件
我有这个 javascript 片段:
var selectName["id1","id2","id3"];
setOnClickSelect = function (prefix, selectName) {
for(var i=0; i<selectName.length; i++) {
var selId = selectName[i];
alert(selId);
$(selId).onchange = function() {
$(selId).value = $(selId).options[$(selId).selectedIndex].text;
}
}
}
但是当我更改 id1 元素的值时,警报总是给我写“id3”。 我可以修复它吗?
编辑: 我用这些语句更改了我的代码片段:
setOnChangeSelect = function (prefix, selectName) {
for(var i=0; i<selectName.length; i++) {
var selId = selectName[i];
$(selId).onchange = (function (thisId) {
return function() {
$(selId).value = $(thisId).options[$(thisId).selectedIndex].text;
}
})(selId);
}
}
但 selId 始终是最后一个元素。
I have this javascript snippet:
var selectName["id1","id2","id3"];
setOnClickSelect = function (prefix, selectName) {
for(var i=0; i<selectName.length; i++) {
var selId = selectName[i];
alert(selId);
$(selId).onchange = function() {
$(selId).value = $(selId).options[$(selId).selectedIndex].text;
}
}
}
But when I change value to my id1 element, the alert wrote me always "id3".
Can I fix it?
EDIT:
I've changed my snippet with these statements:
setOnChangeSelect = function (prefix, selectName) {
for(var i=0; i<selectName.length; i++) {
var selId = selectName[i];
$(selId).onchange = (function (thisId) {
return function() {
$(selId).value = $(thisId).options[$(thisId).selectedIndex].text;
}
})(selId);
}
}
But selId is always the last element.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是由 javaScript Closure 的行为引起的,
selId
已在循环结束时设置为selectName[2]
,这就是您返回“id3”的原因。修复如下,关键是将回调函数包装在另一个函数中以创建另一个闭包。
PS:
var selectName["id1","id2","id3"]
存在语法错误,您应该使用var selectName = ["id1","id2","id3 “];
This is caused by the behavior of javaScript Closure,
selId
has been set to theselectName[2]
at the end of the loop and that's why you get 'id3' back.An fix is as following, the key is wrap the callback function inside another function to create another closure.
Ps: there is synyax error for
var selectName["id1","id2","id3"]
, you should usevar selectName = ["id1","id2","id3"];