How to access recently added HTML elements in jQuery
Here is an example of my problem:
HTML
<p><a class="clickme" href="#">I would like to say:</a></p>
JQuery
$("a.clickme").click(function() {
$('p').append('<div><a href="#" id="say-hello">Hello</a></div>');
});
$("#say-hello").click(function(){
alert('test hello');
});
Here is a script with sample code: http://jsfiddle.net/johnmorris/2UVYd/2/
The first click function works just fine. But a warning (or any other function) will not fire when new elements are added. I basically understand that the added element did not exist when the page loaded, so jQuery does not "see" it ... so the second click function does not work.
I'm just wondering if there is a way around this. And if so, what is it. I don’t seem to understand how to understand this.
You need to wait to assign an event until the element appears:
$("a.clickme").click(function() {
$('p').append('<div><a href="#" id="say-hello">Hello</a></div>');
$("#say-hello").click(function(){
alert('test hello');
});
});
, click - INSIDE click.
@Vega , "", "say-hello" p . , "" DOM p. , . , (, LI UL), . "say-hello" , .
, ( ). ... :
$("a.clickme").click(function() {
$('<div><a href="#" class="say-hello">Hello</a></div>').find('.say-hello')
.click(function(){
alert('test hello');
})
.end()
.appendTo('p');
});
DOM. (, , , "say-hello" .)
, DOM . , 1 100 ID:
<script>
$("a.clickme").click(function() {
var newId = "say-hello" + Math.floor((Math.random()*100)+1);
$('p').append('<div><a href="#" id="' + newId +'">Hello</a></div>');
$("#"+newId).click(function(){
alert('test hello');
})
});
</script>
Please note that I have added the addition of a click handler to an existing click <a>.
Randomization does not guarantee any conflict, but makes the range large enough, and this can be a safe guess. Or just use a counter to make sure there is no ID conflict.