复选框unlick事件Javascript

时间:2015-12-22 18:19:36

标签: javascript html css function

我有问题,复选框取消选中事件。当我取消选中该复选框时,它应该还原。我怎样才能做到这一点?

<body>
<script>
 function change()
    {
        var cb = document.querySelectorAll('input[type="checkbox"]')[0];
        var td = document.querySelectorAll("td[contenteditable]")[0];

        cb.addEventListener("click", function () {
            td.className = td.className + " crossed";
        });
    }
</script>
</body>

3 个答案:

答案 0 :(得分:3)

切换类如:

cb.addEventListener("click", function () {
   td.classList.toggle("crossed");
});

<强> JSFiddle Demo
或者检查是否已选中checkbox

cb.addEventListener("click", function () {
  if(cb.checked) td.classList.add("crossed");
  else td.classList.remove("crossed");
});

<强> JSFiddle Demo

如果您想保留older browser support,可以这样做:

   cb.addEventListener("click", function() {
     if (cb.checked) td.className += " crossed";
     else {
       var tdclass = td.className.split(" "),
         ind = tdclass.indexOf("crossed");
       tdclass.splice(ind, 1).join(" ");
       td.className = tdclass;
     }
   });

<强> JSFiddle Demo

答案 1 :(得分:1)

虽然您已经接受了答案,但我建议对以下内容进行微调:

function change() {
    // querySelector() returns the first element matching the
    // selector (or null, if no matching element is found):
    var cb = document.querySelector('input[type="checkbox"]'),
        td = document.querySelector("td[contenteditable]");

    // use the change event on the check-box:
    cb.addEventListener("change", function () {

        // adds, or removes, the class 'crossed'
        // based on the assessment that follows;
        // of the cb node is checked (true) the
        // class is added (if not already present),
        // otherwise it's removed:
        td.classList.toggle('crossed', cb.checked);
    });
}

答案 2 :(得分:-2)

好的,当你点击它以取消点击时,你想要重新启用它!

$("input[type='checkbox']").props('checked','false') {
    $("input[type='checkbox']").props('checked','true')
}

尝试使用id之类的选择器代替input[type='checkbox']