jQuery的:绑定更改多个复选框 [英] Jquery: Binding change to multiple checkboxes
本文介绍了jQuery的:绑定更改多个复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有关背景一点点,我有多个复选框,每个加权用不同的得分。当复选框被改变,我需要计算分数。我觉得像下面这样的工作,但它并不像在.change事件被正确绑定。
For a little bit of background, I have multiple checkboxes, each weighted with a different "score". When the checkbox is changed, I need to compute the score. I thought something like the following would work but it does not look like the .change event is being bound properly.
$(document).ready(function() {
bindSomeCheckboxes();
});
function bindSomeCheckboxes() {
var score=0;
var checkboxes = {
"id_1" : 3,
"id_2" : 1,
"id_3" : 2,
"id_4" : 5
};
$.each(checkboxes, function(key, value) {
$("#"+key).change(function(key,value) {
if ($("#"+key).is(':checked')) {
//add this ids value to score
} else {
//subtract value from score
}
});
});
}
我知道它是通过数组循环正确的,但在.change警报从未被人看到。
I know that it is looping through the array correctly, but an alert in .change is never being seen.
推荐答案
如果你真的想采取使用IDS的这种方法,我会做编号的一个单独的数组,并做了。加入()
以创建选择。
If you really wanted to take that approach of using IDs, I'd make a separate Array of the ID's, and do a .join()
to create the selector.
需要注意以下几点:
- 而不是
。是(:点击)的
或。是(':检查')
,使用this.checked
。有效得多。 - 事件处理程序有指
事件
一个参数。你有2键,值
。这使得在处理程序键
指的是代替键
事件
对象code>从$。每个()
。 - 里面的处理程序,
这个
是指被点击的人。 - 因为你有
这个
参考元素,你不需要参照键
在$。每个()
。你可以做this.id
。
jQuery中
- Instead of
.is(':clicked')
or.is(':checked')
, usethis.checked
. Much more efficient. - Event handlers in jQuery have one parameter that refers to the
event
. You have 2 forkey,value
. This is makingkey
in the handler refer to thatevent
object instead of thekey
from the$.each()
. - Inside a handler,
this
refers to the one that was clicked. - Because you have
this
reference to the element, you don't need the reference tokey
in the$.each()
. You can just dothis.id
.
function bindSomeCheckboxes() {
var score=0;
var checkboxes = {
"id_1" : 3,
"id_2" : 1,
"id_3" : 2,
"id_4" : 5
};
var arrayOfIds = []; // to store array of ids
$.each(checkboxes,function(key, val) { // populate array with ids
arrayOfIds.push( key );
});
// create a selector of the IDs
$( "#" + arrayOfIds.join(',#') ).change(function() {
// alert the score
alert( checkboxes[ this.id ] );
if ( this.checked ) {
//do something when it is checked
} else {
//do something else
}
});
}
这篇关于jQuery的:绑定更改多个复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文