[英]jQuery function prevents add / remove class on click
I'm trying to have a div get a new class (which makes it expand) when being clicked, and get it back to the old class (which makes it close) when clicking on a cancel link inside that div. 我正在尝试让div在点击时获得一个新类(使其扩展),并在单击该div内的取消链接时将其返回到旧类(使其关闭)。
<div class="new-discussion small">
<a class="cancel">Cancel</a>
</div>
<script>
$('.new-discussion.small').click(function() {
$(this).addClass("expand").removeClass("small");
});
$('a.cancel').click(function() {
$('.new-discussion.expand').addClass("small").removeClass("expand");
});
</script>
Now, adding the expand class works flawlessly, but closing the panel after clicking on the cancel link only works when I remove this code: 现在,添加扩展类可以完美地工作,但是在单击取消链接后关闭面板仅在我删除此代码时才有效:
$('.new-discussion.small').click(function() {
$(this).addClass("expand").removeClass("small");
});
So I guess this must be preventing the second function to work, but I really can't figure out why. 所以我想这必须阻止第二个功能工作,但我真的无法弄清楚为什么。
Any ideas? 有任何想法吗? Thanks!
谢谢!
Try this 尝试这个
$('a.cancel').click(function() {
$('.new-discussion.expand').addClass("small").removeClass("expand");
return false;
});
Reason may be your click event is getting propagated to parent which is also listening to click event. 原因可能是您的点击事件正在传播到父级,也正在侦听点击事件。
Since your a
element is inside the .new-discussion
element, when you click on the a
, it also fires the click
event on the parent element because the event is bubbling up. 由于您
a
元素位于.new-discussion
元素内,因此当您单击a
,它还会触发父元素上的click
事件,因为该事件正在冒泡。
To fix it, you can stop the propagation of the event by calling e.stopPropagation();
要修复它,可以通过调用
e.stopPropagation();
来停止事件的传播e.stopPropagation();
. 。 That will prevent any parent handlers to be executed.
这将阻止执行任何父处理程序。
$('a.cancel').click(function(e) {
e.stopPropagation();
$('.new-discussion.expand').addClass("small").removeClass("expand");
});
Since the link is inside the <div>
, it's using both click methods at once. 由于链接在
<div>
,因此它同时使用了两种单击方法。 It might help to do a check to see if the container is already open before proceeding: 在继续之前检查容器是否已打开可能会有所帮助:
<script>
$('.new-discussion.small').click(function() {
if ($(this).hasClass("small")) {
$(this).addClass("expand").removeClass("small");
}
});
$('a.cancel').click(function() {
$(this).parent('.expand').addClass("small").removeClass("expand");
});
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.