javascript - jQuery - Register an element in the DOM after setting html() - Stack Overflow

I have a div, where I set the innerHTML after a button has been clicked:$('#headerDiv').html(

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 badges
Add a ment  | 

2 Answers 2

Reset to default 4

Delegate 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条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信