我正在尝试制作一个兼容jQuery的组合HTML输入框。
在这个例子中,无论哪个select
发生变化,alert
都会被调用两次。为什么?
给定一个简单的容器节点:
<span id="x"></span>
这里是完全可用的演示:
function el (type) {
return document .createElement (type);
}
function opt (sel, value) {
let node = el ('option');
node .value = value;
node .appendChild (document .createTextNode (value));
sel .appendChild (node);
}
let x = document .getElementById ('x');
let a = el ('select');
let b = el ('select');
x .appendChild (a);
x .appendChild (b);
opt (a, 'a_1');
opt (a, 'a_2');
opt (b, 'b_1');
opt (b, 'b_2');
$(a) .change (function () {$(x) .trigger ('change');});
$(b) .change (function () {$(x) .trigger ('change');});
$(x) .change (function () {alert ('changed');});
el
创建一个新的元素。 - spraff