gpt4 book ai didi

javascript - jQuery 使用 .removeClass() 和 .addClass() 切换类无法正常工作

转载 作者:太空狗 更新时间:2023-10-29 12:27:05 25 4
gpt4 key购买 nike

我已经按照下面描述的代码以我的方式实现了切换。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 链接:

http://jsfiddle.net/nscZA/3/

我正在使用的图像:

image

最佳答案

如果你想这样做,你应该使用 .on 函数来做:原因是,你不会为它没有的类正确绑定(bind)函数(点击事件管理)目前按照你的方式坚持下去。

$(document).on('click','.unCheckedCheckBox',function () {...rest of your function

注意:如果可能,将绑定(bind)放在最近的包装器上,例如提供表包装器和 id 并执行:

$('#mytableid').on('click','.unCheckedCheckBox',function () {

jQuery 1.9.1 示例:http://jsfiddle.net/nscZA/6/

注意不使用 Sprite (不加载)但使用颜色


编辑:具有表 ID 的旧代表:

<table id='mytablewrapper'>

语法略有不同:

$('#mytablewrapper').delegate(".CheckedCheckBox", 'click', function () {

委托(delegate)示例:http://jsfiddle.net/nscZA/7/

注意不使用 Sprite (不加载)但使用颜色

关于javascript - jQuery 使用 .removeClass() 和 .addClass() 切换类无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16360042/

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