admin管理员组

文章数量:1384181

I have been working with jquery for a while so this is quite embarrassing that i'm having issues with this. I created a new element but i can't select it with jquery, what can i do about this? This is the javascript i used to create the element

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

the html is

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

i then tried this

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

but it does not work... i need help here

I have been working with jquery for a while so this is quite embarrassing that i'm having issues with this. I created a new element but i can't select it with jquery, what can i do about this? This is the javascript i used to create the element

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

the html is

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

i then tried this

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

but it does not work... i need help here

Share Improve this question asked Dec 24, 2011 at 11:06 KasperskyKaspersky 951 silver badge11 bronze badges 1
  • Install FireBug on your browser and go to Console tab to see what's wrong. – MahanGM Commented Dec 24, 2011 at 11:10
Add a ment  | 

3 Answers 3

Reset to default 4

Here is a JSFiddle showing that your code works: http://jsfiddle/YqEMa/

It is likely that you have not placed your Javascript within a jQuery "document ready" handler. Wrap your Javascript like this:

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

This will ensure that the DOM has loaded before your Javascript runs.

Also, of course you should ensure that your script is within <script> tags.

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

If you only want the element you've just inserted to be clicked (rather than all #test elements whenever they exist in the page's lifecycle), you can bind the event to the newly created element:

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

本文标签: javascriptCan39t select newly created object with jqueryStack Overflow