如何检测jQuery中的复选框单击

H. *_*nce 4 javascript checkbox jquery onclick onclicklistener

我无法检测何时以及从下面的脚本中点击了哪个复选框:

HTML代码段:

<label for="checkbox[1]"><input type="checkbox" name="checkbox[1]" id="checkbox[1]" class="detectThisChange" value="10.00" checked=""> Amount $10.00</label>
<label for="checkbox[2]"><input type="checkbox" name="checkbox[2]" id="checkbox[2]" class="detectThisChange" value="20.00" checked=""> Amount $20.00</label>
<label for="checkbox[3]"><input type="checkbox" name="checkbox[3]" id="checkbox[3]" class="detectThisChange" value="30.00" checked=""> Amount $30.00</label>
Run Code Online (Sandbox Code Playgroud)

jQuery代码段:

$(document).ready(function() {
  $(window).load(function() {
// ... //
        $('.detectThisChange').change(function(event){
          var targetID = triggerEvent.target.id; // get the id that triggered the event
          var posStart = targetID.indexOf('[') + 1;
          var posEnd = targetID.indexOf(']');
          var i = targetID.substring(posStart, posEnd); // get the index of the id that triggered the event

          if ( $('#checkbox\\['+ i +'\\]').prop('checked') != true ) {
            alert('checkbox ' + i + ' was checked');
          }
          else {
            alert('checkbox ' + i + ' was unchecked');
          }

        });
// ... //
  }); // end .load()
}); // end .ready()
Run Code Online (Sandbox Code Playgroud)

附:

我遇到的问题是我的警报都不起作用.所以这告诉我change()函数没有触发.

Eve*_*ger 11

如果要以动态方式添加此HTML,则应使用.on()方法,如:

$(document).on('change', '.detectThisChange', function() {
    // your code
});
Run Code Online (Sandbox Code Playgroud)

尝试一下,让我知道它是否有帮助.


Sat*_*ngh 6

试试这样吧

$("input[type=checkbox]").is(":checked") // returns boolean checked or unchecked
Run Code Online (Sandbox Code Playgroud)
   var arr = [];
    $("input[type=checkbox]").each(function () {
        var self = $(this);
        if (self.is(':checked')) {
            arr.push(self.attr("id"));
        }
    });
    console.log(arr);
Run Code Online (Sandbox Code Playgroud)

编辑:

$("input[type=checkbox]").on('change', function () {
    var self = $(this);
    if (self.is(":checked")) {
        console.log("checkbox  id =" + self.attr("id") + "is checked ");
    } else {
        console.log("Id = " + self.attr("id") + "is Unchecked ");
    }
});
Run Code Online (Sandbox Code Playgroud)

编辑2:

$("body").on('change','.detectThisChange', function () {
    var self = $(this);
    if (self.is(":checked")) {
        console.log("checkbox  id =" + self.attr("id") + "is checked ");
    } else {
        console.log("Id = " + self.attr("id") + "is Unchecked ");
    }
});
Run Code Online (Sandbox Code Playgroud)

工作演示

学习jQuery:简单易用的jQuery教程博客