javascript 如何在 jQuery 中创建多个复选框处理程序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17441439/
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-10-27 08:20:22  来源:igfitidea点击:

How to create multiple checkbox handlers in jQuery?

javascriptjquery

提问by Mythul

I have these 2 checkboxes:

我有这两个复选框:

<form action="">
    <input id="bikeCheckbox" type="checkbox" name="bikeCheckbox" value="Bike">I have a bike<br>
    <input id="carCheckbox" type="checkbox" name="carCheckbox" value="Car">I have a car
</form>

The events for each checkbox:

每个复选框的事件:

jQuery(function () {
$("#carCheckbox").click(function () {
    if($("#carCheckbox").is(":checked")) {
        alert("it works");
    }
})
});

jQuery(function () {
$("#carCheckbox").click(function () {
    if($("#bikeCheckbox").is(":checked")) {
        alert("it works");
    }
})
});

Now what I want to do is create a foror some kind of loop to create event handlers for multiple checkboxes. So far I am stuck at this code:

现在我想做的是创建一个for或某种循环来为多个复选框创建事件处理程序。到目前为止,我被困在这段代码中:

jQuery(function () {
var infoArray = ["car", "bike"];

for(var i = 0; i < infoArray.length; i++) {
    var id = "#" + infoArray[i] + "Checkbox";

    $(id).click(function () {
        var myCheckbox = "#" + infoArray[i] + "Checkbox;
        if($(myCheckbox).is(":checked")) {
            alert("it works");
        }
    })
}
});

Any help is greatly appreciated.

任何帮助是极大的赞赏。

回答by Timmetje

You don't need to create an array to save all these values and loop these. And you definitely don't need a function for each checkbox!

您不需要创建一个数组来保存所有这些值并循环这些值。而且您绝对不需要每个复选框的功能!

Add a class to your checkboxes you want to check, for example :

在您要检查的复选框中添加一个类,例如:

<form action="">
    <input id="bikeCheckbox" class="mycheckbox" type="checkbox" name="bikeCheckbox" value="Bike">I have a bike<br>
    <input id="carCheckbox" class="mycheckbox" type="checkbox" name="carCheckbox" value="Car">I have a car
</form>

Then you can easily loop like this:

然后你可以像这样轻松循环:

jQuery(function () {
    // Whenever any of these checkboxes is clicked
    $("input.mycheckbox").click(function () {
        // Loop all these checkboxes which are checked
        $("input.mycheckbox:checked").each(function(){
            alert("it works");
            // Use $(this).val() to get the Bike, Car etc.. value
        });
    })
});

回答by Ankur Bhadania

<form action="">
    <input id="bikeCheckbox" class="mybox" type="checkbox" name="bikeCheckbox" value="Bike">I have a bike<br>
    <input id="carCheckbox" class="mybox" type="checkbox" name="carCheckbox" value="Car">I have a car
</form>
$('#save_value').click(function(){
$('.mybox:checked').each(function(){
     alert($(this).val());
}); });
$('#save_value').click(function(){
$('.mybox:checked').each(function(){
     alert($(this).val());
}); });

you try to add class name same for ever check box and used the

您尝试添加永远相同的类名复选框并使用

回答by Shinov T

You can try this also

你也可以试试这个

<script TYPE="text/javascript">
     jQuery(function () {
       var infoArray = ["car", "bike"];

       for(var i = 0; i < infoArray.length; i++) {
            var id = "#"+infoArray[i]+"Checkbox";
            $(id).click(function () {
               if($(id).is(":checked")) {
                 alert("it works");
               }
            })
       }
     });
</script>

回答by DDK

use JQuery's eachfunction

使用 JQuery 的每个函数

jQuery(function () {
    $(":checkbox").click(function () {
         $(':checkbox:checked').each(function(i){
            alert("it works");
          });
     });
}

回答by Raghurocks

if you want to do it by some grouping, like if you want to see only in some of the checkbox in a group, you can use the class name like this below

如果你想通过一些分组来做到这一点,比如如果你只想在组中的某些复选框中看到,你可以使用下面这样的类名

<form action="">
    <input id="bikeCheckbox" class="myCheckBoxGroup" type="checkbox" name="bikeCheckbox" value="Bike">I have a bike<br>
    <input id="carCheckbox" class="myCheckBoxGroup" type="checkbox" name="carCheckbox" value="Car">I have a car
</form>
jQuery(function () {
    $(".myCheckBoxGroup").click(function () {
        $(".myCheckBoxGroup").each(function(){
            if($(this).is(":checked")) {
                alert("this is checked");
            }
        });
    })
});

回答by Jaimin

Try this.

试试这个。

<input id="chk_bikeCheckbox"  type="checkbox" onclick='UpdateIdinHF(this);' name="bikeCheckbox" value="Bike">
<input id="chk_carCheckbox" class="mycheckbox" onclick='UpdateIdinHF(this);' type="checkbox" name="carCheckbox" value="Car">






 function UpdateIdinHF(obj) {
        var id = $(obj).attr('id');
        var name = $(obj).attr('name');
        var value = parseInt($(obj).attr('value'));
        var IsChecked = $(obj).is(':checked');

            $('input[id*="chk_' + name + '"]').each(function () {
                if (parseInt($(this).val()) != 0) {
                    if (IsChecked == true) {
                        $(this).attr('checked', 'checked');

                    }
                    else {
                        $(this).removeAttr('checked');

                    }
                }
            });

    }

回答by Tombeau

are you looking for something like this?

你在寻找这样的东西吗?

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 M.Reza

You don't need to define classes. Use the following snippet to directly access to the checkbox you have clicked.

您不需要定义类。使用以下代码段直接访问您单击的复选框。

$(document).on("click", "input[type='checkbox']", function (e) {
     console.log(e.target);
});