Assigning click event to dynamically added buttons

后端 未结 5 1843
孤街浪徒
孤街浪徒 2020-12-29 17:13

I am creating some buttons dynamically and assigning them IDs.

When ever someone clicks that button I want to collect the ID and from there perform some task.

5条回答
  •  北荒
    北荒 (楼主)
    2020-12-29 17:31

    If you are dynamically adding buttons, think about using ".live()". Whenever the specified event happens, it follows the html elements up the tree until it is handled. This is more efficient if you have a lot of elements also because the event isn't assigned to the element itself. You need to assign a class or something to the buttons to identify them, let's say 'dynamicButton', so change this:

    
    

    to this:

    
    

    And you can listen to events with this code:

    $('input.dynamicButton').live('click', function (event) {
            alert($(this).attr('id'));
        });
    

    This one handler will be called anytime a button with the class 'dynamicButton' is clicked no matter how it is added to the page.

提交回复
热议问题