on() method is always alive to the selectors till end. which means if creating event directly with element like $(selector).click(function{}); then when user creating multiple elements dynamically on the same page has to apply click event again on the selector element. Event created with on() method then automatically creates the events for new elements with are dynamically get inserted on the page.
$("ul.menu li").click(function(){
document.location = $(this).attr("loc");
});
instead of
$("ul.menu").on("click","li",function(){
document.location = $(this).attr("loc");
});
If any new <li> element is inserts on <ul> then on() method automatically assigns the click event to the new <li> element. live() and delegate() methods are deprecated method of on() method.
|
<script type="text/javascript">
$(function(){
$("ul").on("click","li",function(){
alert($(this).html());
});
$("button").click(function(){
$("ul").append("<li>"+($("ul li").length+1)+"</li>");
});
});
</script>
Click on the <li> tag and button
<ul>
<li>1</li>
<li>2</li>
</ul>
<button>INSERT <LI></button>
|