jQuery的:绑定更改多个复选框 [英] Jquery: Binding change to multiple checkboxes

查看:77
本文介绍了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 。有效得多。

  • jQuery中
  • 事件处理程序有指事件一个参数。你有2 键,值。这使得在处理程序指的是代替事件对象code>从 $。每个()

  • 里面的处理程序,这个是指被点击的人。

  • 因为你有这个参考元素,你不需要参照 $。每个()。你可以做 this.id

  • Instead of .is(':clicked') or .is(':checked'), use this.checked. Much more efficient.
  • Event handlers in jQuery have one parameter that refers to the event. You have 2 for key,value. This is making key in the handler refer to that event object instead of the key 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 to key in the $.each(). You can just do this.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屋!

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