gpt4 book ai didi

jquery - 使用 jQuery 只允许一个事件 div

转载 作者:行者123 更新时间:2023-12-03 22:54:44 25 4
gpt4 key购买 nike

假设我有 3 个 div,每个 div 都带有 item 类,并且一次只有一个可以具有 active 类。例如:

<div class="item active">1</div>
<div class="item">2</div>
<div class="item">3</div>

我有一个 jQuery 绑定(bind)代码,可以在单击事件上激活 div:

$(document).ready(function () {
$('.item').bind('click', function() {
addClass('active');
// now I need to remove active class from the previous selected item
});
});

进行内务管理的最佳方法是什么,我可以从任何其他可能处于事件状态的 div 中删除事件类?

提前致谢。

最佳答案

你需要使用$(this).addClass,不仅仅是它自己,你还可以使用active<从所有元素中删除active 事先类 - 像这样:

$(document).ready(function () {
$('.item').bind('click', function() {
// remove the active class from all elements with active class
$('.active').removeClass('active')
// add active class to clicked element
$(this).addClass('active');
});
});

关于jquery - 使用 jQuery 只允许一个事件 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7370946/

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