不能用jquery选择新创建的对象

Can't select newly created object with jquery

本文关键字:创建 对象 jquery 选择 新创建 不能      更新时间:2023-09-26

我一直在使用jquery一段时间,所以这是相当尴尬的,我有这个问题。我创建了一个新元素,但我不能用jquery选择它,我该怎么办?这是我用来创建元素

的javascript代码
$('<div id="test">blah</div>').insertAfter('#ref');

的HTML是

<html>
<head>
</head>
<body>
<div id="ref"></div>
</body>
</html>

i then try this

$('#test').click(function(){
    $(this).remove();
});

但它不工作…我需要帮助

下面是显示代码工作的JSFiddle: http://jsfiddle.net/YqEMa/

很可能你没有把你的Javascript放在jQuery"document ready"处理程序中。像这样包装你的Javascript:

$(function() {
    $('<div id="test">blah</div>').insertAfter('#ref');
    $('#test').click(function() {
        $(this).remove();
    });
});

这将确保在Javascript运行之前DOM已经加载。

当然,你也应该确保你的脚本在<script>标签内。

   $('#test').live('click', function(){
     $(this).remove();
   });

如果您只想单击刚刚插入的元素(而不是所有#test元素,无论它们是否存在于页面的生命周期中),您可以将事件绑定到新创建的元素:

$('<div id="test">blah</div>')
    .click(function(){
        $(this).remove();
    })
    .insertAfter('#ref');