选择插入元素时出现问题

时间:2011-06-06 07:33:38

标签: jquery jquery-selectors

我想选择我用after()插入的元素,但我无法选择它。

在Firebug控制台中,我可以使用$('.new-tree-node-close')来获取<span.new-tree-node-close>,但在我的页面中我无法获得它。

<ul> 
  <li class="tree-l2"><a class="reference internal" href="#">One</a></li> 
  <li class="tree-l2"><a class="reference internal" href="#">Two</a></li> 
  <li class="tree-l2"><a class="reference internal" href="#">There</a></li>
  <li class="tree-l2-new">
      <div class="new-tree-node-l2">New</div>
  </li> 
</ul> 
$(document).ready(function() {
    //When User click 'New',remove it and insert new input box and 'Close'
    $('.new-tree-node-l2').click(function(event) {
        $(this).parent(':last').after('<input name="" class="new-tree-node-title"><span class="new-tree-node-close">[Close]</span>');
        $(this).remove();    
    });

    //When user click the 'Close',do something..
    $('.new-tree-node-close').click(function(event) {
        alert("Do Something...");
    });
});

Here is the main code and more detail in the jsfiddle.

1 个答案:

答案 0 :(得分:6)

将代码更改为

//When user click the 'Close',do something..
$('.new-tree-node-close').live('click', function(event) {
    alert("Do Something...");
});

使用live代替点击。