2009-12-01 93 views
0

样品的HTML标记以下的jQuery选择父问题

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

JS功能:

function close_comments() { 
var comments_wrapper = $(this).closest('.answer_comments'); 
comments_wrapper.slideUp(); 
} 

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

回答

3

检查什么 “这”,它可能指的是功能本身,而不是元素

变化

<p class="close_comments" onclick="close_comments()">Close</p> 

<p class="close_comments" onclick="close_comments(this)">Close</p> 

和功能

function close_comments(element) { 
    var comments_wrapper = $(element).closest('.answer_comments'); 
    comments_wrapper.slideUp(); 
} 

,看看会发生什么

+0

这样的作品,非常感谢。 – stef 2009-12-01 20:53:59

5

你是对的,你正在使用this错了。这将是正确的用法,如果你使用jQuery绑定事件:您目前的解决方案

$('.close_comments').click(function() { 
    var comments_wrapper = $(this).closest('.answer_comments'); 
    comments_wrapper.slideUp(); 
}); 

,你必须做

function close_comments(obj) { 
    var comments_wrapper = $(obj).closest('.answer_comments'); 
    comments_wrapper.slideUp(); 
} 

<p class="close_comments" onclick="close_comments(this);">Close</p> 
+0

+1用于显示“绑定”的*右键*方式。 – 2009-12-01 20:48:23