adding jQuery click events to dynamically added content

后端 未结 4 592
礼貌的吻别
礼貌的吻别 2020-11-28 13:33

I have a table with multiple rows and columns populated by php and mySQL. For some of the td\'s I\'m adding jQuery click-events in the document.ready function to let the use

相关标签:
4条回答
  • 2020-11-28 14:02

    You can use .delegate() function which attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.

    0 讨论(0)
  • 2020-11-28 14:06

    Use the live event handler. It doesn't handle all events, but it does handle the click event. The handler will be bound to all current and future elements that match the selector.

    $('tr.clickable').live( 'click', function() {
       ...
    });
    
    0 讨论(0)
  • 2020-11-28 14:29

    You want to use live events, which were introduced in 1.3.

    $("tr.clickable").live("click", function() {
       //add input fields
    });
    
    $("span#addNewRow").live("click", function() {
       $("table").append('<tr><td class="clickable"></td> ... </tr>')
    });
    

    UPDATE: Note that as of jQuery 1.7, live() is deprecated. Use on() instead. And in some cases, delegate() may be a better choice. See the comments below.

    Example of how to use .on():

    $("table").on("click", "tr.clickable", function() {
       //add input fields
    });
    
    0 讨论(0)
  • 2020-11-28 14:29

    You would have to add the event listeners after the elements are inserted.

    If you are using JQuery you could use the jQuery library livequery which allows you to add events to elements that are not yet in the dom so that you dont have to rebind events when you insert something new into the dom.

    0 讨论(0)
提交回复
热议问题