javascript,突然间jquery没有检测到我的复选框被选中
http://pastebin.com/r30Wfvi3
突然之间就停止了工作。
var showMyLocation = document.createElement('input'); showMyLocation.type = "checkbox"; showMyLocation.className = "checkboxForRange"; showMyLocation.id = "showMyLocation"; $$.children("#showMyLocation").html('Vis min posisjon :
').append(showMyLocation); $('#' + showMyLocation.id).change(function () { //location console.log("clicked"); if ($(this).is(":checked")) { console.log("y"); GarageHandler.showPosition(); } else { console.log("n"); GarageHandler.hidePosition(); } });
这是给定代码的输出:
"clicked" "n", "clicked" "n", "clicked" "n", "clicked" "n", etc.
应该是这样的:
"clicked" "y", "clicked" "n", "clicked" "y", "clicked" "n", etc.
有谁知道什么是错的?
从我可以看到你有一个带有id showMyLocation
的容器元素,你要附加复选框,但你的复选框也有相同的id,这是无效的,因为元素的id必须是唯一的。 在您的情况下,当您注册更改处理程序时,它将被注册到容器元素而不是复选框,因此更改处理程序内部不会引用复选框
您不必为input元素添加id来为其添加更改处理程序,您只需使用dom元素引用即可
$(showMyLocation).change(function () { //location console.log("clicked", this); if (this.checked) { console.log("y"); GarageHandler.showPosition(); } else { console.log("n"); GarageHandler.hidePosition(); } });
演示: 小提琴 , 另一种方式