Jquery:将更改绑定到多个复选框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3924809/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:21:18  来源:igfitidea点击:

Jquery: Binding change to multiple checkboxes

jquerybinding

提问by ftdysa

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.

对于一点背景,我有多个复选框,每个复选框都有不同的“分数”。当复选框更改时,我需要计算分数。我认为像下面这样的事情会起作用,但看起来 .change 事件没有被正确绑定。

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

I know that it is looping through the array correctly, but an alert in .change is never being seen.

我知道它正确地循环遍历数组,但从未看到 .change 中的警报。

采纳答案by user113716

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.

如果您真的想采用这种使用 ID 的方法,我会创建一个单独的 ID 数组,然后执行 a.join()来创建选择器。

Some things to note:

一些注意事项:

  • 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 keyin the handler refer to that eventobject instead of the keyfrom the $.each().
  • Inside a handler, thisrefers to the one that was clicked.
  • Because you have thisreference to the element, you don't need the reference to keyin the $.each(). You can just do this.id.
  • 而不是.is(':clicked').is(':checked'),使用this.checked。效率更高。
  • jQuery 中的事件处理程序有一个参数是指event. 你有 2 个key,value。这是key在处理程序中引用该event对象而不是key来自$.each().
  • 在处理程序中,this指的是被点击的那个。
  • 因为您有this对元素的引用,所以不需要key$.each(). 你可以这样做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
        }
    });
} 

回答by BrunoLM

I recommend you to add a container and select all checkboxes at once.

我建议您添加一个容器并一次选中所有复选框。

And as for your question, the signature of the event is wrong, the correct is function(e){}. Also, you have to check if the element is checked, and not clicked.

至于你的问题,事件的签名是错误的,正确的是function(e){}。此外,您必须检查元素是否被选中,而不是被点击。

$("#chk").change(function(e){
    if ($(this).is(":checked"))
        alert("checked");
    else
        alert("not checked");
});

To make it easier, use a container

为方便起见,请使用容器

Sample HTML

示例 HTML

<div id="checks">
    <input type="checkbox" id="chk1" />
    <input type="checkbox" id="chk2" />
    <input type="checkbox" id="chk3" />
    <input type="checkbox" id="chk4" />
</div>

And for the scores, I prefer to set data on the elements, example:

对于分数,我更喜欢在元素上设置数据,例如:

$("#chk1").data("Score", 3);
$("#chk2").data("Score", 1);
$("#chk3").data("Score", 2);
$("#chk4").data("Score", 5);

$("#checks :checkbox").change(function(e){
    if ($(this).is(":checked"))
        alert("checked Score: " + $(this).data("Score"));
    else
        alert("not checked Score: " + $(this).data("Score"));
});

回答by Fenton

I would recommend obtaining the checkboxes in a more natural way...

我建议以更自然的方式获取复选框...

$("input[type='checkbox']").change(function () { 
    alert("Event is bound");
});

If you want to restrict which checkboxes to use, you could add a class, although if you can avoid adding unnecessary classes, your html will be cleaner.

如果您想限制使用哪些复选框,您可以添加一个类,尽管如果您可以避免添加不必要的类,您的 html 会更干净。

回答by Floyd

try use 'bind' and ':checked'

尝试使用 'bind' 和 ':checked'

$.each(checkboxes, function(key, value) {
    $(this).bind('change', function() {
      if ($(this).is(':checked')) {
        //do something when it is checked
      } else {
        //do something else
      }
    });
});