Javascript 是否可以将复选框更改与类的组合使用?

Javascript 是否可以将复选框更改与类的组合使用?,javascript,jquery,html,checkbox,Javascript,Jquery,Html,Checkbox,这是我的代码,带有复选框,其中包含one和two类,如下所示 <input type="checkbox" class="one" value="1"> <br/> <input type="checkbox" class="two" value="2"> <br/> <input type="checkbox" class="one" value="3"> <br/> 我的问题是,如何在事件处理程序中也使用类 我试过这种

这是我的代码,带有复选框,其中包含onetwo类,如下所示

<input type="checkbox" class="one" value="1">
<br/>
<input type="checkbox" class="two" value="2">
<br/>
<input type="checkbox" class="one" value="3">
<br/>
我的问题是,如何在事件处理程序中也使用类

我试过这种方法

$(document).on('change', '.one .[type="checkbox"]', function(event, data){
    alert('checked ');
});
$(document).on('change', '.two .[type="checkbox"]', function(event, data){ 
    alert('checked ');
});

这是一个错误的选择器:

 '.[type="checkbox"]'  
属性选择器前面不能有点


现在回答您的问题,您可以使用以下方法:

 '.one[type="checkbox"]'
 // make sure you don't have any space in between.

您可以为每个复选框指定一个通用类名,并且可以在该类上绑定一个更改事件:

$('.commonClass[type=“checkbox”]')。在('change',函数(事件,数据){
如果(选中此项){
log(this.classList[1]+'checked');
}
});




是的,这是可能的

您可以使用此选择器:

.one[type="checkbox"]
要将其分解,此选择器将匹配具有
的任何元素。一个
类作为类型属性等于
复选框

您还可以将
[type=“checkbox”]
作为选择器,然后在更改处理程序中检查elements类。如果您希望在不同的复选框之间具有稍微不同的功能,这将非常有用-

$(document).on('change', '[type="checkbox"]', function(event, data){
    var classes = $(this).attr('class').split(' '); // may be multiple classes - split them into an array
    if ( $.inArray( 'one', classes ) ){
      alert('.one was changed!');
    } else {
      alert('some other checkbox was changed!');
    }
});

对于这个简单的示例,这可能有些过分,但它允许您进一步自定义不同的复选框。

首先删除一个额外的“.”在这之前
[type=“checkbox”]
,然后只使用
.one.two这样的类作为事件侦听器,您将根据需要获得结果

$(document).on('change', '[type="checkbox"]', function(event, data){
    var classes = $(this).attr('class').split(' '); // may be multiple classes - split them into an array
    if ( $.inArray( 'one', classes ) ){
      alert('.one was changed!');
    } else {
      alert('some other checkbox was changed!');
    }
});