Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

jquery - how to make live click event on new added DOM

i am a live() user and i know somehow live() is deprecated. i've tried to use bind() to have the event on new added dom working, but it's not.

can you please tell me how to do bind() properly ? or is there any other method to do this task?

this is the html:

<table>
    <tr>
        <td> hi there <span class="click">click me</span></td>
    <tr>
    <tr>
        <td> hi there2 <span class="click">click me</span></td>
    <tr>
    <tr class="end">
        <td></td>
    </tr>
</table>
<button class="add_new">add new row</button>  

this is the js :

var new_row = '<tr><td> hi there, new row! <span class="click">click me</span></td><tr>';

$('.add_new').click(function() {
    $('.end').before(new_row);    
});


$('.click').bind('click', function() {
   alert('clicked');
});

if possible, i want to use native jquery's method and not plugins. this is my jsfiddle http://jsfiddle.net/bondythegreat/z3uXH/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to use the dynamic version of jQuery's .on() or .delegate().

$('table').on('click', '.click', function() {
    // your code here
});

For dynamic behavior using delegated event handling, the basic idea is that the first select (in the jQuery object) must be a static parent object that is not dynamically created after the event handler is installed. The second selector which is passed as the second argument to .on() is a selector that matches the specific item you want the event handler on. These items can be dynamically created after the event handler is installed.

Using .click() or .bind() gets you static event handlers that only work on objects that are present at the time the code is initially run.

To make this code more robust, I'd suggest two things. First, don't use a class name like "click" that is very easy to confuse with an event. Second, put an id on your table, so that ID can be referenced in the first selector rather than the very generic "table" that may accidentally be active on other tables in your page.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...