javascript - In jQuery, how to attach events to dynamic html elements? -


this question has answer here:

suppose have jquery code attaches event handler elements class "myclass". example:

$(function(){     $(".myclass").click( function() {         //     }); }); 

and html might follows:

<a class="myclass" href="#">test1</a> <a class="myclass" href="#">test2</a> <a class="myclass" href="#">test3</a> 

that works no problem. however, consider if "myclass" elements written page @ future time.

for example:

<a id="anchor1" href="#">create link dynamically</a> <script type="text/javascript"> $(function(){     $("#anchor1").click( function() {         $("#anchor1").append('<a class="myclass" href="#">test4</a>');     }); }); </script> 

in case, "test4" link created when user clicks on a#anchor1.

the "test4" link not have click() handler associated it, though has class="myclass".

any idea how can fix this?

basically, write click() handler once , have apply both content present @ page load, , content brought in later via ajax/dhtml.

i adding new answer reflect changes in later jquery releases. .live() method deprecated of jquery 1.7.

from http://api.jquery.com/live/

as of jquery 1.7, .live() method deprecated. use .on() attach event handlers. users of older versions of jquery should use .delegate() in preference .live().

for jquery 1.7+ can attach event handler parent element using .on(), , pass selector combined 'myclass' argument.

see http://api.jquery.com/on/

so instead of...

$(".myclass").click( function() {     // }); 

you can write...

$('body').on('click', 'a.myclass', function() {     // }); 

this work tags 'myclass' in body, whether present or dynamically added later.

the body tag used here example had no closer static surrounding tag, parent tag exists when .on method call occurs work. instance ul tag list have dynamic elements added this:

$('ul').on('click', 'li', function() {     alert( $(this).text() ); }); 

as long ul tag exists work (no li elements need exist yet).


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -