javascript,突然jquery没有检测到我的复选框被选中 [英] javascript, all of a sudden jquery doesn't detect that my checkbox is checked

查看:93
本文介绍了javascript,突然jquery没有检测到我的复选框被选中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

http://pastebin.com/r30Wfvi3

突然停止工作。

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();
        }
    });

这是给定代码的输出:

"clicked"
"n",
"clicked"
"n",
"clicked"
"n",
"clicked"
"n",
etc.

应该像:

"clicked"
"y",
"clicked"
"n",
"clicked"
"y",
"clicked"
"n",
etc.

有没有人知道什么错了。

Does anyone know whats wrong?.

推荐答案

从我可以看到你有一个容器元素的id showMyLocation ,你将添加复选框,但你的复选框也有相同的id,不是作为元素的id必须是唯一的。在你的情况下,所以当你注册更改处理程序,它被注册到容器元素而不是复选框,所以 this 在更改处理程序中不引用复选框

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

您不需要为输入元素添加一个id来为其添加更改处理程序,您只需使用dom元素引用

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();
    }
});

演示:小提琴另一种方式

这篇关于javascript,突然jquery没有检测到我的复选框被选中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆