简体   繁体   English

触发输入复选框的change()事件不会触发所有事件处理程序

[英]Firing change() event for input checkboxes doesn't trigger all event handlers

We have around twenty input checkboxes, and they're divided into six groups using CSS classes. 我们大约有二十个输入复选框,并且使用CSS类将它们分为六个组。 We added an event handler for the change event on each of the six classes, and then we added a final event handler for the change event on the input element itself. 我们在六个类中的每个类上为change事件添加了一个事件处理程序,然后在输入元素本身上为change事件添加了一个最终事件处理程序。 It looks like this: 看起来像这样:

(HTML) (HTML)

<input type="checkbox" name="cbox" class="A"> 1
<input type="checkbox" name="cbox" class="A"> 2
<input type="checkbox" name="cbox" class="B"> 3
<input type="checkbox" name="cbox" class="B"> 4
// ...
// checkboxes for classes C, D, E
// ...
<input type="checkbox" name="cbox" class="F"> 20

(jQuery) (jQuery的)

$('.A').change(function() {
    // doesn't get called
});

$('.B').change(function() {
    // doesn't get called
});

$('.C').change(function() {
    // doesn't get called
});

$('.D').change(function() {
    // doesn't get called
});

$('.E').change(function() {
    // doesn't get called
});

$('.F').change(function() {
    // doesn't get called
});

$('input[name="cbox"]').change(function() {
    // this one gets called
});

$('input[name="cbox"]').change();

When I finally call $('input[name="cbox"]').change() , the only event handler that gets called is the last one, ie 当我最终调用$('input[name="cbox"]').change() ,唯一被调用的事件处理程序是最后一个,即

$('input[name="cbox"]').change(function() {
    // this one gets called
});

All the other event handlers that I added (for classes A, B, C, D, E and F) don't get called. 我添加的所有其他事件处理程序(对于A,B,C,D,E和F类)都不会被调用。 Why is this? 为什么是这样? Shouldn't $('input[name="cbox"]').change() trigger all of the event handlers, and not just the one? $('input[name="cbox"]').change()触发所有事件处理程序,而不仅仅是一个?

Try this, 尝试这个,

$('input.A').change(function(event) {
      alert($(this).val());
});

jsfiddle 的jsfiddle

I dont know why its not working, Working to me i posted fiddle for sandbox 我不知道为什么它不起作用,对我来说我为沙盒贴了小提琴

 let classnamelist = ['a','b','c','d','e','f','g','l','m','n','o','p','q','r','s','y',] for(let i = 0; i<classnamelist.length; i++){ let el = $('<input>').attr({ 'type':'checkbox', 'name':'cbox' }).addClass(classnamelist[i]); $('body').append(el); $('.'+classnamelist[i]).change(function(){ alert($(this).is(':checked')) }) } $('input[name=cbox]').change(); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

If you're adding the checkboxes dynamically you should try : 如果要动态添加复选框,则应尝试:

$(document).on('change', '.A', function() {
   // do stuff
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM