【发布时间】:2017-10-27 18:25:57
【问题描述】:
我正在以编程方式创建多个选择元素,每个选择元素中有多个选项。我想以编程方式为每个选择元素分配其自己的 onchange 函数,该函数将提醒我选择元素的相应 id。
$(document).ready(function () {
// Headers indicate how many select elements I need.
// In this example, they are only used to initialize a unique select.id
for (var ndx = 0; ndx < headers.length; ndx++) {
var header = headers[ndx];
const rowName = header.innerHTML;
var select = document.createElement("select");
var options = ["Contains", "Equals", "Starts with", "More than", "Less than", "Between", "Empty",
"Doesn't contain", "Doesn't equal", "Doesn't start with", "Is not more than", "Is not between", "Is not empty"];
select.id = rowName + "-select";
options.forEach(function(option) {
var element = document.createElement("option");
element.value = option;
element.innerHTML = option;
select.appendChild(element);
});
select.onchange = function () {
alert("select.id: " + select.id);
}
}
}
但是,在更改任何选择元素的选项时,只有最后一个选择元素的 id 会显示在警报中。这可能是我不熟悉的 javascript 引用问题吗?感谢您的帮助。
【问题讨论】:
-
你不能用
this代替select吗? -
发生这种情况的原因是因为您每次迭代都更改了 select.id。
select.id = rowName + "-select";,所以它只输出最后一个。 JS 闭包确实存储对范围外变量的引用,但它们不会像您现在希望的那样存储旧值。 -
@AP。哇,你是对的!这对于为什么只显示最后一个元素的 id 也是有意义的。谢谢!
标签: javascript html node.js web onchange