使用jquery获取父div的父级的id

时间:2013-05-08 07:26:37

标签: jquery ajax codeigniter

我有以下代码,我需要在jquery中获得帖子的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!
});

3 个答案:

答案 0 :(得分:7)

使用closest("div.post")

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

closest返回与您的选择器匹配的第一个元素,因此它在您的情况下返回div.commentor,而.find在其中找不到任何.post,因此{ {1}}。

答案 1 :(得分: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

答案 2 :(得分: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

相关问题