jquery选择父问题

ste*_*tef 0 jquery jquery-selectors

下面的示例html标记

<div class="container answer_comments">
<p class="comment_text">Hey that's not cool.</p>
<p class="comment_attribs">By Anonymous User on 01 Dec</p>
<p class="comment_text">Is that really why?</p>
<p class="comment_attribs">By person on 27 Nov</p>
<p class="close_comments" onclick="close_comments()">Close</p>
</div>
Run Code Online (Sandbox Code Playgroud)

JS功能:

function close_comments() {
var comments_wrapper = $(this).closest('.answer_comments');
comments_wrapper.slideUp();
}
Run Code Online (Sandbox Code Playgroud)

.answer_comments不会关闭.是因为即时通讯使用$(这)错了?这个div在页面上重复多次,实现我想要做的最好的方法是什么?

Dav*_*und 5

this说错了,你是对的.如果您使用jQuery绑定事件,那将是正确的用法:

$('.close_comments').click(function() {
    var comments_wrapper = $(this).closest('.answer_comments');
    comments_wrapper.slideUp();
});
Run Code Online (Sandbox Code Playgroud)

对于您当前的解决方案,您必须这样做

function close_comments(obj) {
    var comments_wrapper = $(obj).closest('.answer_comments');
    comments_wrapper.slideUp();
}
Run Code Online (Sandbox Code Playgroud)

<p class="close_comments" onclick="close_comments(this);">Close</p>
Run Code Online (Sandbox Code Playgroud)