最近没有处理动态添加的内容

时间:2015-02-24 19:17:33

标签: javascript jquery html

我正在尝试将.closest()与我的HTML页面一起使用。我有这个HTML:

<body>
  <div class="listcontainer">
    //Content
    <div class="button">Ok</div>
  </div>
</body>

当用户点击&#39; .button&#39; ,我通过ajax调用动态地将这个HTML添加到上面的HTML。成功时,ajax调用会将以下html附加到body:

<div class="listpanel">
    //Content
</div>

所以,我在listcontainer下面有listpanel,它们都在body体内。现在我使用.closest as:

$listpanel = $('.listpanel'); 
$div = $listpanel.closest('.listcontainer');

但不知何故,最接近的是选择html元素而不是listcontainer。我不确定为什么会这样。有人可以帮我这个吗? 谢谢。

编辑:这就是我的Ajax调用的样子:

$('.button').click(function(){
      $.ajax({
            url:"listpanel.html",
            cache: false,
            dataType: "html",
            success:function(data)
            {
                    $('body').append(data);
            }
     });
});

2 个答案:

答案 0 :(得分:2)

如果您将div.listpanel附加到正文,则它不在div .listcontainer中。因此,最接近的不会找到它。你需要搜索兄弟姐妹:

var myDiv = $('.listpanel').siblings('.listcontainer').first();

或将其附加到div .listcontainer,然后使用nearest()方法

答案 1 :(得分:0)

.closest遍历祖先DOM树。它不会看兄弟姐妹或钻进兄弟姐妹的子树。这是预期的功能。

http://api.jquery.com/?s=closest

相关问题