问题
http://pastebin.com/r30Wfvi3
All of a sudden that just stopped working.
var showMyLocation = document.createElement('input');
showMyLocation.type = "checkbox";
showMyLocation.className = "checkboxForRange";
showMyLocation.id = "showMyLocation";
$$.children("#showMyLocation").html('<p style="float:left">Vis min posisjon :</p>').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();
}
});
Here's the output the of the given code:
"clicked"
"n",
"clicked"
"n",
"clicked"
"n",
"clicked"
"n",
etc.
It should be like:
"clicked"
"y",
"clicked"
"n",
"clicked"
"y",
"clicked"
"n",
etc.
Does anyone know whats wrong?.
回答1:
From what I can see you have an container element with id showMyLocation
to which you are appending the checkbox, but your checkbox also has the same id which is not valid as id of an element must be unique. In your case so when you register the change handler it is getting registered to the container element not to the checkbox so this
inside the change handler does not refer the checkbox
You need not have to given an id to the input element to add a change handler for it, you can just use the dom element reference
$(showMyLocation).change(function () { //location
console.log("clicked", this);
if (this.checked) {
console.log("y");
GarageHandler.showPosition();
} else {
console.log("n");
GarageHandler.hidePosition();
}
});
Demo: Fiddle, another way
来源:https://stackoverflow.com/questions/20184024/javascript-all-of-a-sudden-jquery-doesnt-detect-that-my-checkbox-is-checked