通过 jQuery 添加类后,jQuery 不删除类
今天早上我似乎在 removeClass
方面遇到了一些麻烦。首先,我单击一个 div
添加类 'containerhover'
,然后当我单击关闭按钮时,它不会删除刚刚添加到 div 的类
。
我不知道这是否与仅添加到 dom 而没有实际编码到 HTML 中有关。请有人帮忙。
HTML
<div class="container"></div>
jQuery
$(function() {
$('.container').click(function(e) {
var mythis = $(this);
mythis.addClass("containerhover");
mythis.find('.backface').addClass("bfhover");
mythis.find('.album').addClass("ahover");
});
$('.closealbum').click(function(e) {
$('.container').removeClass('containerhover');
});
});
I seem to have run into a bit of trouble this morning with removeClass
. First I click a div
to add Class 'containerhover'
, then when I click the close button it will not remove the class that it has just added to the div
.
I don't know if this has something to do with it being added to the dom only and not being actually coded into the HTML. Please can someone help.
HTML
<div class="container"></div>
jQuery
$(function() {
$('.container').click(function(e) {
var mythis = $(this);
mythis.addClass("containerhover");
mythis.find('.backface').addClass("bfhover");
mythis.find('.album').addClass("ahover");
});
$('.closealbum').click(function(e) {
$('.container').removeClass('containerhover');
});
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用
.on()
将事件附加到容器,然后仅当单击.closealbum
元素时才激活它。另外,添加event.stopPropagation()
方法以防止事件进一步冒泡:.closealbum
元素不存在而引起的。点击
事件。e.stopPropagation()
,事件会冒泡,第一个事件也会被触发,撤消第二个事件的removeClass。演示:http://jsfiddle.net/knCR8/1/
Use
.on()
, to attach the event to the container, and activate it only if the.closealbum
element is clicked. Also, add theevent.stopPropagation()
method to prevent the event from bubbling further:.closealbum
element does not exist when binding theclick
event.e.stopPropagation()
, the event bubbles up, and the first event will also be triggered, undoing the second event's removeClass.Demo: http://jsfiddle.net/knCR8/1/