The <a> tag jquery click event added at run time does not fire

I am adding a tag at runtime using jquery.

<a id=add class=add href=#>Test</a>

I want to fire the click event of this tag, but it does not fire.

I have already tried

$('#add').bind('click', function(e) {

e.preventDefault();
  alert('hello');

});

but nothing happens.

+1
source share
3 answers

You need to bind it with .live ()

$('#add').live('click', function(e) {
  e.preventDefault();
  alert('hello');
});

The .live () method can affect elements that have not yet been added to the DOM using event delegation.

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

+7
source

Perhaps you should use valid XHTML:

<a id="add" class="add" href="#">Test</a>

And in jQuery:

$('#add').live('click', function(e) {
    e.preventDefault();
    alert('hello');
});
+3
source

jquery 1.7

$( 'document').on( "click",'#step',  function() {
               console.log("Clicking step"); 
});
+2

Source: https://habr.com/ru/post/1733118/


All Articles