2016-08-23 20 views
-1

我在循环中打印下面的HTML代码片段。使用parent()在jQuery中获取值

<div class = "commentbox"> 
    <input type="hidden" name="postid" value="${p.postid}" /> 
    <input type="hidden" name="username" value="${username}" /> 
     <input type="hidden" name="source" value="user_home" /> 
    <textarea name="comment" cols="40" rows="1" class="add_comment" 
     placeholder="Add a comment..."></textarea> 
    <div class="post_con"> 
     <button type="submit" class="postcomment">Post</button> 
    </div> 
</div> 

我有这样的jQuery的片而言在<button class="postcomment">一下,当我想获得的<input name="postid">值。

$(".postcomment").click(function(){ 
    var parent = $(this).parent(); 
    var postid = parent.find(".postid").val(); 
    console.log(postid); 
}); 

但是,它记录undefined。我怎样才能得到postid的价值?

+0

我没有看到postid类。你的意思是reviewid? – Evus

+0

@Evus嘿!犯了一个错误。再次检查出来。 – ProgramAllDay

+0

我知道这是回答,但你的jq会工作,如果你加强了一个父母...... var parent = $(this).parent()。parent();''postcomment'是在一个div parent1),那么这是在另一个div - 'commentbox'(parent2)中。 - 你正试图在'post_con' div中找到()'''nearest()'更好:) – Scott

回答

3

您可以使用.closest()遍历至commentbox元素,它是元素postcommentpostid元素的共同父元素。

然后,如您在name属性中指定postid那么您可以使用Attribute value selector

$(".postcomment").click(function() { 
    var parent = $(this).closest('.commentbox'); 
    var postid = parent.find("[name=postid]").val(); 
    console.log(postid); 
}); 
+0

哇!这很简单。感谢您的快速帮助 – ProgramAllDay