Javascript jQuery函数可防止在单击时添加/删除类

Javascript jQuery函数可防止在单击时添加/删除类,javascript,jquery,html,css,Javascript,Jquery,Html,Css,我试图让一个div在被单击时获得一个新类(使其扩展),并在单击该div内的取消链接时将其返回到旧类(使其关闭) <div class="new-discussion small"> <a class="cancel">Cancel</a> </div> <script> $('.new-discussion.small').click(function() { $(this).addClass("exp

我试图让一个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>
所以我猜这一定阻止了第二个函数的工作,但我真的不明白为什么

有什么想法吗? 谢谢

试试这个

$('a.cancel').click(function() {
    $('.new-discussion.expand').addClass("small").removeClass("expand");
    return false;
});

原因可能是您的单击事件正在传播到父级,而父级也在侦听单击事件。

由于链接位于
中,因此它同时使用两种单击方法。在继续之前,检查容器是否已打开可能会有所帮助:

<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>

$('.new discussion.small')。单击(函数(){
if($(this).hasClass(“小”)){
$(this.addClass(“expand”).removeClass(“small”);
}
});
$('a.cancel')。单击(函数(){
$(this).parent('.expand').addClass(“small”).removeClass(“expand”);
});

由于您的
a
元素位于
元素内。新讨论
元素中,当您单击
a
时,它还会在父元素上触发
单击
事件,因为该事件正在冒泡

要修复它,可以通过调用
e.stopPropagation()停止事件的传播。这将阻止执行任何父处理程序

$('a.cancel').click(function(e) {
    e.stopPropagation();
    $('.new-discussion.expand').addClass("small").removeClass("expand");
});

你知道你可以使用
.toggleClass
而不是添加和删除,对吗?是的,但是也不起作用。推测:因为
'a.cancel'
'之内。新讨论。小'
是不是注册了
$('.new discussion.small')).cancel
?在我上面的评论中,我可能是错的,但我认为这可能是需要检查的,因为你说当你删除
$('.new discussion.small')时它可以工作。单击(function(){$(this.addClass(“expand”).removeClass(“small”)return
false与调用
e.preventDefault()
e.stopPropagation()
,但只会阻止事件在jQuery处理程序的上下文中冒泡。@user2264587谢谢!!此链接位于我的一个FAV中;)在本例中,我认为因为它是一个锚标记,并且可能有一个href属性与之关联,所以最好返回false。无论如何,由你决定。e、 stopPropagation()在这里也适用。
$('a.cancel').click(function(e) {
    e.stopPropagation();
    $('.new-discussion.expand').addClass("small").removeClass("expand");
});