I have a div, where I set the innerHTML after a button has been clicked:
$('#headerDiv').html('Wele [<a href=\'javascript:void(0);\' id=\'logout_button\'>Logout</a>]');
However, the new element logout_button
isn't registered in the DOM
, so I can't capture click events using the traditional $('#logout_button').click()
.
Is it possible to register logout_button
in the DOM
just after it's been set with the html()
method?
Thanks!
I have a div, where I set the innerHTML after a button has been clicked:
$('#headerDiv').html('Wele [<a href=\'javascript:void(0);\' id=\'logout_button\'>Logout</a>]');
However, the new element logout_button
isn't registered in the DOM
, so I can't capture click events using the traditional $('#logout_button').click()
.
Is it possible to register logout_button
in the DOM
just after it's been set with the html()
method?
Thanks!
Share Improve this question asked Jun 6, 2013 at 23:51 BrettBrett 12k35 gold badges136 silver badges222 bronze badges2 Answers
Reset to default 4Delegate the event
$('#headerDiv').on('click', '#logout_button', function() {
// Your code
});
This will make sure the event is attached to the dynamically added
element by the concept of event bubbling.
If delegation isn't your cup of tea, you can bind your click handler to the button before attaching the button. Do that by creating DOM elements and appending 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 ensuring you are adding valid elements to the DOM.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745131799a4613007.html
评论列表(0条)