如何更正复选框并在选中时显示
how to correct check checkbox and display if is checked
我使用此代码在单击 1 个或多个复选框时显示一些文本 (Checked
)。
我使用 on
因为复选框是动态创建的。
好像只有IE Edge无法处理。我必须在复选框上单击两次才能显示 Checked
文本。在所有其他浏览器中,它会立即运行。
真的不知道代码有什么问题
<input type="checkbox" class="rafcheckbox" value="1" />
<input type="checkbox" class="rafcheckbox" value="2" />
<input type="checkbox" class="rafcheckbox" value="3" />
<div class="cb-buttons" style="display:none">Checked</div>
<script>
$(document).on('click','.rafcheckbox',function() {
var $checkboxes = $('.rafcheckbox').change(function() {
var anyChecked = $checkboxes.filter(':checked').length != 0;
$(".cb-buttons").toggle(anyChecked);
});
});
</script>
Fiddle: https://jsfiddle.net/g5tp4kjm/
- 由于您已经有了元素的委托,只需将其更改为更改事件处理程序即可。
- 在该逻辑中,切换隐藏 class,但如果未选中任何元素,则强制其隐藏 class。
$(document).on('change','.rafcheckbox',function() {
$('.cb-buttons').toggleClass('hide', $('.rafcheckbox:checked').length < 1);
});
.hide { display: none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="rafcheckbox" value="1" />
<input type="checkbox" class="rafcheckbox" value="2" />
<input type="checkbox" class="rafcheckbox" value="3" />
<div class="cb-buttons hide">Checked</div>
让我们换个方式试试。
$(document).on('click','.rafcheckbox',function() {
if($('.rafcheckbox').is(':checked'))
{
//do whatever you want
}
else
{
//do the opposite
}
});
我使用此代码在单击 1 个或多个复选框时显示一些文本 (Checked
)。
我使用 on
因为复选框是动态创建的。
好像只有IE Edge无法处理。我必须在复选框上单击两次才能显示 Checked
文本。在所有其他浏览器中,它会立即运行。
真的不知道代码有什么问题
<input type="checkbox" class="rafcheckbox" value="1" />
<input type="checkbox" class="rafcheckbox" value="2" />
<input type="checkbox" class="rafcheckbox" value="3" />
<div class="cb-buttons" style="display:none">Checked</div>
<script>
$(document).on('click','.rafcheckbox',function() {
var $checkboxes = $('.rafcheckbox').change(function() {
var anyChecked = $checkboxes.filter(':checked').length != 0;
$(".cb-buttons").toggle(anyChecked);
});
});
</script>
Fiddle: https://jsfiddle.net/g5tp4kjm/
- 由于您已经有了元素的委托,只需将其更改为更改事件处理程序即可。
- 在该逻辑中,切换隐藏 class,但如果未选中任何元素,则强制其隐藏 class。
$(document).on('change','.rafcheckbox',function() {
$('.cb-buttons').toggleClass('hide', $('.rafcheckbox:checked').length < 1);
});
.hide { display: none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="rafcheckbox" value="1" />
<input type="checkbox" class="rafcheckbox" value="2" />
<input type="checkbox" class="rafcheckbox" value="3" />
<div class="cb-buttons hide">Checked</div>
让我们换个方式试试。
$(document).on('click','.rafcheckbox',function() {
if($('.rafcheckbox').is(':checked'))
{
//do whatever you want
}
else
{
//do the opposite
}
});