JQuery - register an element in the DOM after installing html ()

I have a div where I set innerHTML after clicking a button:

$('#headerDiv').html('Welcome [<a href=\'javascript:void(0);\' id=\'logout_button\'>Logout</a>]'); 

However, the new logout_button element logout_button not registered in the DOM , so I cannot capture click events using the traditional $('#logout_button').click() .

Is it possible to register logout_button in the DOM immediately after installing it using the html() method?

Thanks!

+4
source share
2 answers

Delegate event

 $('#headerDiv').on('click', '#logout_button', function() { // Your code }); 

This will make sure that the event is attached to the dynamically added element according to the concept of the event bubble.

+4
source

If delegation is not your cup of tea, you can attach a click handler to a button before attaching a button. Do this by creating DOM elements and adding them:

 var btn = $('<a />').text('Logout').attr({ "href": "javascript:void(0);", "id": "logout_button" }).click(function (e) { // do logout stuff e.preventDefault(); return false; }); $('#headerDiv').append(btn); 

This has the added bonus of adding valid elements to the DOM.

+1
source

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


All Articles