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
3 Answers
Reset to default 4Here 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
版权声明:本文标题:javascript - Can't select newly created object with jquery - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744477549a2607965.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论