[英]jQuery toggling the class with .removeClass() and .addClass() not working properly
我已经按照下面的代码实现了切换。 HTML:
<table>
<thead>
<tr>
<th class="selectCol"><div class="unCheckedCheckBoxAll"></div></th>
<th class="nosCol">Products</th>
</tr>
</thead>
<tr>
<td><div class="unCheckedCheckBox"></div></td>
<td>ABCD</td>
</tr>
<tr>
<td><div class="unCheckedCheckBox"></div></td>
<td>PQRS</td>
</tr>
</table>
CSS:
.unCheckedCheckBox, .unCheckedCheckBoxAll
{
width: 25px;
height: 25px;
margin-top: -4px;
background: transparent url(http://i.stack.imgur.com/tsaPu.png) top left no-repeat;
}
.CheckedCheckBox,.CheckedCheckBoxAll
{
width: 25px;
height: 25px;
margin-top: -4px;
background: transparent url(http://i.stack.imgur.com/tsaPu.png) 0 -60px;
}
jQuery的:
$(".CheckedCheckBox").click(function () {
$(this).removeClass('CheckedCheckBox').addClass('unCheckedCheckBox');
if ($(".CheckedCheckBox").length == 0) {
$('.CheckedCheckBoxAll').removeClass('CheckedCheckBoxAll').addClass('unCheckedCheckBoxAll');
}
});
$(".unCheckedCheckBox").click(function () {
$(this).removeClass('unCheckedCheckBox').addClass('CheckedCheckBox');
if ($(".unCheckedCheckBox").length == 0) {
$('.unCheckedCheckBoxAll').removeClass('unCheckedCheckBoxAll').addClass('CheckedCheckBoxAll');
}
});
$(".CheckedCheckBoxAll").click(function () {
$(this).removeClass('CheckedCheckBoxAll').addClass('unCheckedCheckBoxAll');
$('.CheckedCheckBox').removeClass('CheckedCheckBox').addClass('unCheckedCheckBox');
});
$(".unCheckedCheckBoxAll").click(function () {
$(this).removeClass('unCheckedCheckBoxAll').addClass('CheckedCheckBoxAll');
$('.unCheckedCheckBox').removeClass('unCheckedCheckBox').addClass('CheckedCheckBox');
});
现在的问题是,当我单击未选中的div时,它变为选中的div,但是当我单击选中的div时,尽管选中了类,但它进入了未选中的功能。 帮我。 我没有什么问题。
这是jsfiddle链接:
我正在使用的图像:
如果要这样做,则应使用.on
函数:理由,您将无法通过当前方式将函数(单击事件管理)正确绑定到当前不包含的类。
$(document).on('click','.unCheckedCheckBox',function () {...rest of your function
注意:如果可能,将绑定放在最近的包装器上,例如给表包装器和id并执行:
$('#mytableid').on('click','.unCheckedCheckBox',function () {
jQuery 1.9.1示例: http : //jsfiddle.net/nscZA/6/
注意不使用精灵(不加载),但使用颜色
编辑:具有表ID的旧委托:
<table id='mytablewrapper'>
语法略有不同:
$('#mytablewrapper').delegate(".CheckedCheckBox", 'click', function () {
委托示例: http : //jsfiddle.net/nscZA/7/
注意不使用精灵(不加载),但使用颜色
Bind事件保存在页面加载时,因此,如果您希望class .CheckedCheckBox
有操作,则在添加类时必须添加绑定,而在删除类时必须删除绑定。 但这不是一个好方法。 当然,需要使用toggleClass。
这里是我所做的事情的小提琴: http : //jsfiddle.net/nscZA/8/
我在checkbox
上绑定了一个偶数,因此您不必添加/删除它
$(".checkBox").click(function () {
$(this).toggleClass('isChecked');
if ($(".checkBox").length == $(".isChecked").length) {
$('.checkBoxAll').addClass('checkAllChecked');
}else{
$('.checkBoxAll').removeClass('checkAllChecked');
}
});
它添加了选中的类,并检查是否选中了所有复选框。
我恳求您探索我的解决方案,并询问是否有您不理解的问题。
请注意,我对您的html类/ css进行了一些更改。
欢呼
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.