【问题标题】:javascript, all of a sudden jquery doesn't detect that my checkbox is checkedjavascript,突然jquery没有检测到我的复选框被选中
【发布时间】:2013-11-25 03:03:30
【问题描述】:

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.

有谁知道怎么回事?

【问题讨论】:

  • 请贴出问题中的代码和现场演示来重现问题。
  • 看起来你有一个容器和一个具有相同 id 的输入字段

标签: javascript jquery checkbox


【解决方案1】:

据我所知,您有一个 ID 为 showMyLocation 的容器元素,您将复选框附加到该元素,但您的复选框也具有相同的 ID,该 ID 无效,因为元素的 ID 必须是唯一的。在您的情况下,当您注册更改处理程序时,它会注册到容器元素而不是复选框,因此更改处理程序内的this 不会引用复选框

你不需要给输入元素一个 id 来为它添加一个更改处理程序,你可以使用 dom 元素引用

$(showMyLocation).change(function () { //location
    console.log("clicked", this);
    if (this.checked) {
        console.log("y");
        GarageHandler.showPosition();
    } else {
        console.log("n");
        GarageHandler.hidePosition();
    }
});

演示:Fiddleanother way

【讨论】:

  • 我爱你!我想我真的很累 atm :o
猜你喜欢
  • 2014-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-02
  • 2017-11-15
  • 2012-11-02
  • 1970-01-01
  • 2012-01-26
相关资源
最近更新 更多