开发者

Add click function to dynamically created html tags

So I have a div that contains a number of other divs. Each of these other divs has a class called record. I only use this class to select all of these divs.

<div id = "resultContainer">
   <div class="record">result1</div>
   <div class="record">result2</div>
   <div class="record">result3</div>
   <div class="record">result4</div>
<开发者_StackOverflow;/div>

I also add a click event=

$(".record").click(function(e) {
        do stuff here....
    });

Now I want to dynamically add another div.

$("#resultContainer").append("<div class='record'>result5>/div>");

But now that click event is not added to the record.

My idea was to create a function called update() that executed the $(".record.... code and call the function each time I added a record. But then the original divs do the action more than once!

How do I get all of my divs, regardless of when they were added, to before the do stuff here... exactly once when clicked?

thanks!

In addition, I also have buttons on the dynamic div. So a solution that was able to handle something lik this: $(".save").button({ icons: { primary: 'ui-icon-disk' }, text: false }); would be preferable.


Don't use .live() in this case. This is a perfect situation for jQuery's .delegate() method, which is more efficient.

$("#resultContainer").delegate('.record','click',function() {
    // do stuff here...
});

Only clicks inside the resultContainer need to be processed to see if they match .record, where .live() will need to process every click on the page.


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

Attach a handler to the event for all elements which match the current selector, now and in the future.

$(".record").live("click", function(e) {
    //do stuff here... 
});


As of jQuery 1.7 you should use on() instead of live() or delegate(). From the documentation:

As of jQuery 1.7, the .on() method provides all functionality required for attaching event handlers.

The on() method should be attached to a static parent or document:

$(document).on( 'click', '.record', function(e) {
    // do stuff here....
});


Take a look at the jQuery live() function

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

You can add an event listener for all div, regardless of changes in the page


Try live() method. Instead of:

$(".record").click(function(e) {
    do stuff here....
});

Try this:

$(".record").live(function(e) {
    do stuff here....
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜