如何检测jQuery中的复选框单击 [英] How to detect a checkbox click in jQuery

查看:90
本文介绍了如何检测jQuery中的复选框单击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法检测到以下脚本中何时单击了哪个复选框:

I cannot detect when and which checkbox gets clicked from script below:

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>

jQuery代码段:

jQuery Snippet:

$(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()

已添加:

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

The problem I am experiencing is that none of my alerts work. So that tells me the change() function is not firing.

推荐答案

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

If you are adding this HTML dinamically, you should use the .on() method, like:

$(document).on('change', '.detectThisChange', function() {
    // your code
});

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

Give it a try and let me know if it helps.

这篇关于如何检测jQuery中的复选框单击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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