gpt4 book ai didi

javascript - 我如何更正这个 jquery/js 复选框代码

转载 作者:行者123 更新时间:2023-11-28 19:26:06 25 4
gpt4 key购买 nike

我一直很难弄清楚这些代码。

复选框代码的功能如下:

有一个全局复选框(全选)和子(单个)复选框。如果选中(全局)复选框,则所有(子)复选框也将被选中,一个 div 将显示,如果全局未选中,它将取消选中(子)复选框,并且 div 将隐藏(jquery hide并展示)。将显示选中的复选框的数量。

这就是问题所在;如果取消选中子复选框,则全局复选框仍保持选中状态,如果选中所有子复选框,则也应立即选中全局复选框。

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">    </script>
<div id="mydiv" style="display:none;">RESTORE | DELETE
<span>Checked: </span>
<span id="counter"></span>
</div>
<input type="checkbox" id="global">
<br>
<input type="checkbox" class="child">
<input type="checkbox" class="child">
<input type="checkbox" class="child">
<input type="checkbox" class="child">
<input type="checkbox" class="child">
<input type="checkbox" class="child">
<input type="checkbox" class="child">

$(document).ready(function() {
$('#global').click(function() {
$('.child').prop('checked', $(this).is(':checked'));

if ($(this).is(':checked'))
$('#mydiv').show();
else
$('#mydiv').hide();

count();
});

$('.child').change(function() {
var checkedLength = $('.child:checked').length;
if (checkedLength > 0)
$('#mydiv').show();
else
$('#mydiv').hide();
count();
});
});

var count = function() {
var i = $('input.child:checked').length;
$('#counter').html(i);
}

感谢所有支持。提前致谢。

最佳答案

将 #global 更改为 .global

这应该有效。只需要一个事件。

$(document).ready(function() {
var child = $('.child');
var global = $('.global');

$('input').on("change", function() {
//check if checkbox is the global one
if($(this).hasClass("global")) {
//if yes, then set all childs to checked true, if not, then to false
($(this).prop('checked')) ? child.prop('checked', true) : child.prop('checked', false);
} else {
var oneChecked = false;
//every change on a checkbox go though all childboxes an check if on of them is checked
child.each(function() {
if($(this).prop('checked') == true) {
oneChecked = true;
}
});
//if one was checked global has to be checked, if no one was checked it has to be false
(oneChecked) ? global.prop('checked', true) : global.prop('checked', false);
}
});
});

关于javascript - 我如何更正这个 jquery/js 复选框代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27863839/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com