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

Clicking on One Button Cancels a Click Event of Another (Outer) Button in jQuery

本文关键字:单击 按钮 外部 另一个 事件 jQuery 一个 可取消      更新时间:2023-09-26

我有一个允许用户发表评论的帖子,但默认情况下,评论textarea是隐藏的,直到用户单击Comment按钮。注释文本区域有一个 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>

j查询

$('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会删除此事件。The comment_cancel_button按预期隐藏comment_wrapper,但之后单击Comment不会slideToggle它。我必须刷新。我如何以正确的方式处理这个问题?

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

你藏.comment_body_wrapper,给.comment_wrapper

您隐藏了'.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')

问题是使用

"注释"按钮,您可以使用类.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();
})