What's the best way to event handle dynamically created HTML? [duplicate]

帅比萌擦擦* 提交于 2019-12-26 21:38:38

问题


It's very easy to event-handle when dealing with items the document has from the get go:

$(document).ready(function() {
    $('.element-in-question').on("event", function (event) {
        //do what you need to do during the event
    });
});

My problem is how would I best deal with dynamic elements. For example, let's say I dynamically load notifications, some of which are friend requests during an AJAX request. Would I create the event-handler in the success callback, or would I do it somewhere else?

The way I would currently go about it:

$(document).ready(function() {
    $.ajax({
        url: '/friendships/requests',
        type: 'GET', 
        success: function(responseData) {
            //dynamically create your elements (with classes accepted and rejected)
            $('.accepted, .rejected').on("click", function(event) {
                //do what is needed in this event
            });
        }
   });
});

Is this the idiomatic way to go about it, or is there another way I probably should be going about it?


回答1:


use jquery's "on" merhod to bind event handler to parent element (which will not change) and pass a selector of the element you want to listen to:

$('.parent').on('event', '.child', handlerFunction);



回答2:


If you dynamically create an element, such as a 'button', that was not on the page before, handle it like this:

$(function() {

    (function() {
        $('body').append('<button id="newButton">Hello World!</button>');
    })();

    $('body').on('click','#newButton',function() {

        console.log($(this).html()); //"Hello World!"

    });


});



回答3:


I think this is the (partly) right approach. You cannot and should not apply eventhandlers to objects that might or might not be available, even if possible.

If the situation would involve 10000 different eventhandlers, they should be only available when present in dom. When removed the eventhandler should be removed as well.

The way you do it is rudimentary but correct.

2 other thoughts. If you bind the listener in the ajax callback you might add to the "stack" of events, since they are not replaced. Not a good thing. If the ajax query will happend more than once, do not add it again, if not removed first.

Another aproach might be to just add them to all pages, if this is a small page/application and first check that the element exist. Like so:

if ($('#id').size() > 0) { 
// bind events for #id here
}


来源:https://stackoverflow.com/questions/20820808/whats-the-best-way-to-event-handle-dynamically-created-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!