Attaching jQuery to buttons after document.ready

2020-07-30 03:47发布

I'm writing some code based on the following article:

jQuery - Dynamically Adding Form Elements

What I would like to do is to have buttons on each row to add a new row below the row the button is on.

This works OK for the first row, because there is code in document.ready to attach a jQuery function to the button.

However, the button in the second row is added dynamically - how do I attach the same function to this dynamically added button?

Thanks.

Matt.

标签: jquery
3条回答
三岁会撩人
2楼-- · 2020-07-30 04:25

use live() for dynamically added objects

instead of

$('.button').click(function(){});

use

$('.button').live('click',function(){});
Binds a handler to an event (like click) for all current - and

future - matched element. Can also bind custom events.

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

查看更多
聊天终结者
3楼-- · 2020-07-30 04:46

From the JQuery docs...

As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().

on() function example:

$(selector).on(event,childSelector,function)

查看更多
够拽才男人
4楼-- · 2020-07-30 04:48

use function live(), this way it will bind events to created elements after document ready

查看更多
登录 后发表回答