2013-05-08 105 views
1

我有以下代码,我需要有在jquery中发布的ID!请帮助我。得到使用jquery的父div的父母的ID

foreach($posts->result() as $post){ 
    echo "<div class='post' id='$post->id' >"; 
     echo $post->content; 
     echo "<div class='commentor' id='commentor' >"; 
      echo "<input type='text' class='commentor_input' />"; 
     echo "</div>"; 
    echo "</div>"; 
} 

我试过使用代码波纹管得到的文章的代码,但不工作!

$('.commentor_input').change(function(e){ 
    e.stopImmediatePropagation(); 
    var comment = $(this).val(); 
    var post_id = $(this).closest("div").find(".post").attr("id"); 
    alert(post_id); // alerts Undefined! 
}); 

回答

7

使用closest("div.post")

var post_id = $(this).closest("div.post").attr("id"); 

closest回报您的选择相匹配的第一个元素,所以它返回你的情况div.commentor.find找不到它里面的任何.post,因此undefined

+0

嗯,我没有得到3个downvotes我对这个答案了。任何downvoter请解释吗? – Dogbert 2013-05-08 07:43:57

+0

看起来像2个downvoters今天被禁止从这个网站。 – Dogbert 2013-05-15 13:37:41

2

只需将.find()更改为.parent()即可。

$('.commentor_input').change(function(e){ 
    e.stopImmediatePropagation(); 
    var comment = $(this).val(); 
    var post_id = $(this).closest("div").parent(".post").attr("id"); 
    alert(post_id); // alerts Undefined! 
}); 

DEMO

0

尝试:

$('.commentor_input').change(function(e){ 
    e.stopImmediatePropagation(); 
    var comment = $(this).val(); 
    var post_id = $(this).parents("div.post").attr("id"); 
    alert(post_id); // alerts Undefined! 
}); 

文档jquery.parents