while experimenting with jquery, I created this html and javascript.
<body>
<div id="results">
<div class="mylinkdiv">
<a class="mylinkclass" href="#">8</a>
: This is supposed to be a toaster.
<br>
<a class="mylinkclass" href="#">14</a>
: with a toaster maybe.
<br>
<a class="mylinkclass" href="#">51</a>
: If we're really creative.
<br>
</div>
</div>
<button id="remove" type="button" > Remove</button>
<button id="add" type="button" > Add</button>
</body>
the javascript has a function to popup a message containing the link text.It also has a function to add some links to the div .A function named remove which removes the inner div .
$(document).ready(function(){
$('.mylinkclass').click(function(){
getLinkText(this);
});
$('#remove').click(function(){
removeContents();
});
$('#add').click(function(){
addContents();
});
});
function getLinkText(that){
var txt = $(that).text();
var num = parseInt(txt);
alert('num='+num);
return false;
}
function addContents(){
$('#results').append('<a class="mylinkclass" href="#">70</a> new line1 <br>');
$('#results').append('<a class="mylinkclass" href="#">77</a> new line2<br>');
}
function removeContents(){
$('.mylinkdiv').remove();
}
When I click on the links in the original html page ( ie the 3 links ) ,the alert box pops up.
When I click the add button,it adds two new links to the div.But,when I click on those newly added links ,the alert does not pop up!
I can’t understand why..can someone tell me?
Use .on if you are using jQuery 1.7 or .delegate if you are using jQuery 1.6
Demo
Another way you can do this is you clone your existing element, Demo
In the second case event listener will also be copied and you dont need to use .on or .delegate.