单击一个按钮取消jQuery中的另一个(外部)按钮的单击事件

时间:2014-10-08 14:40:20

标签: javascript jquery

我有一个帖子允许用户发表评论,但默认情况下隐藏评论textarea,直到用户点击Comment按钮为止。评论textarea有一个 SendCancel按钮。 Cancel按钮会隐藏textarea,但在此之后,点击Comment按钮会再次起作用,直到您刷新页面为止。

HTML

<div class='post'>
    <div class='p_body'>
        <div class = 'comment_body_wrapper'>
            <div class = 'comment_wrapper'>
                <textarea class="comment_content" rows = '2' maxlength="480" name="comment_content" placeholder="Your thoughts on this..."></textarea>
                <div class = 'comment_buttons_wrapper'>
                    <div class='comment_buttons'>
                        <button class="submit_comment btn" type="submit">Send</button>
                        <button class="comment_cancel_button btn" type="submit">Cancel</button>
                    </div>
                </div>
            </div>
        </div>
        <div class = 'post_footer'>
            <button class='btn post_comment' value = '1'>Comment </button>
        </div>
    </div>
</div>

的jQuery

$('body').on('click', '.post_comment', function(){
    var $this = $(this);
    var $comment=$this.closest('.post').find('.comment_body_wrapper').find('.comment_wrapper');
    $comment.slideToggle(); 
    $comment.find('.comment_content').focus();
})

$('body').on('click', '.comment_cancel_button', function(){
    var $this = $(this);
    $this.closest('.comment_body_wrapper').hide();
})

如果我点击Comment按钮,它肯定会切换它(显示或隐藏),但点击Cancel会删除此事件。 comment_cancel_button 按预期隐藏comment_wrapper,但在点击Comment之后不会slideToggle。我必须刷新。我该如何正确处理这个问题?

3 个答案:

答案 0 :(得分:2)

我似乎隐藏了与你展示不同的元素。

您隐藏.comment_body_wrapper并显示.comment_wrapper

答案 1 :(得分:1)

您隐藏'.comment_body_wrapper',但显示其子'.comment_wrapper':)

http://jsfiddle.net/TrueBlueAussie/mjqs6ces/1/

$(document).on('click', '.post_comment', function(){
    console.log('.post_comment');
    var $this = $(this);
    var $comment=$this.closest('.post').find('.comment_body_wrapper .comment_wrapper');
    $comment.slideToggle(); 
    $comment.find('.comment_content').focus();
});


$(document).on('click', '.comment_cancel_button', function(){
    var $this = $(this);
    $this.closest('.comment_body_wrapper').find('.comment_wrapper').hide();
});

注意:您可以将两个查找缩短为一个选择器.find('.comment_body_wrapper .comment_wrapper')

答案 2 :(得分:1)

问题在于,使用“注释”按钮切换具有类.comment_wrapper的元素,但在“取消”按钮中,您隐藏了具有不同类comment_body_wrapper的元素。

然后你隐藏.comment_wrapper,并尝试切换.comment_wrapper,这是一个不同的元素,所以不起作用。

在这两种情况下,您必须使用相同的类,然后它才能正常工作。

    $('body').on('click', '.post_comment', function(){
    var $this = $(this);
    var $comment=$this.closest('.post').find('.comment_body_wrapper');
    $comment.slideToggle(); 
    $comment.find('.comment_content').focus();
})

$('body').on('click', '.comment_cancel_button', function(){
    var $this = $(this);
    $this.closest('.comment_body_wrapper').hide();
})
相关问题