Turning live() into on() in jQuery

后端 未结 5 2207
盖世英雄少女心
盖世英雄少女心 2020-11-21 22:28

My application has dynamically added Dropdowns. The user can add as many as they need to.

I was traditionally using jQuery\'s live() method to detect w

5条回答
  •  旧时难觅i
    2020-11-21 23:02

    The on documentation states (in bold ;)):

    Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on().

    Equivalent to .live() would be something like

    $(document.body).on('change', 'select[name^="income_type_"]', function() {
        alert($(this).val());
    });
    

    Although it is better if you bind the event handler as close as possible to the elements, that is, to an element being closer in the hierarchy.

    Update: While answering another question, I found out that this is also mentioned in the .live documentation:

    Rewriting the .live() method in terms of its successors is straightforward; these are templates for equivalent calls for all three event attachment methods:

    $(selector).live(events, data, handler);                // jQuery 1.3+
    $(document).delegate(selector, events, data, handler);  // jQuery 1.4.3+
    $(document).on(events, selector, data, handler);        // jQuery 1.7+
    

提交回复
热议问题