javascript, all of a sudden jquery doesn't detect that my checkbox is checked

陌路散爱 提交于 2019-12-23 06:06:18

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!