2016-08-23 7 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> 

은 내가 <button class="postcomment"> 클릭 할 때 나는 <input name="postid"> 값을 좀하고 싶습니다이 jQuery를 조각이있다.

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

그러나 undefined은 기록합니다. postid 값을 얻으려면 어떻게해야합니까?

+0

postid 클래스는 볼 수 없습니다. reviewid입니까? – Evus

+0

@ 남편 이봐! 실수를하다. 다시 확인해보십시오. – ProgramAllDay

+0

이 답변을 알고 있지만 부모가 한 명 더 계단을 마련했다면 jq가 작동했을 것입니다 ...'var parent = $ (this) .parent(). parent();''postcomment'는 div 안에 있습니다. parent1) 그러면 다른 div -'commentbox' (parent2) 안에 있습니다. - 당신은'post_con' div에서'find()'를 시도했습니다 ...'closest()'는 더 낫습니다 :) – Scott

답변

3

.closest()을 사용하면 postcommentpostid 요소의 공통 상위 요소 인 commentbox 요소까지 트래버스 할 수 있습니다.

postidname 속성에 지정 했으므로 Attribute value selector을 사용할 수 있습니다.

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

와우! 그것은 간단했다. 빠른 도움에 감사드립니다. – ProgramAllDay

관련 문제