how to attach jquery event handlers for newly injected html?

我们两清 提交于 2019-12-06 19:06:33

问题


How would I use .on() if the HTML is not generated yet? The jQuery page says

If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page.

But I'm not really sure how to do that. Is there a way to "reload" the event handler?

So if I had

$(document).ready(function(){
    $('.test').on('click', function(){
        var id = $(this).attr('id');
        console.log("clicked" + id);
    });
generatePage();
});

where generatePage() creates a bunch of divs with .test, how would I rebind .on()?

I'm aware similar questions have been asked, but I didn't find what I was looking for after a quick search.


回答1:


Use .on like in the example below. One can presume that the body-tag is always available so it's safe to attach the event handler to body and delegate the events to the selector, in this case .test.

$(document).ready(function(){
    $('body').on('click', '.test', function(){ // Make your changes here
        var id = $(this).attr('id');
        console.log("clicked" + id);
    });

    generatePage();
});

Or if generatePage() is also generating the html, head and body tags use document as your selector.

$(document).ready(function(){
    $(document).on('click', '.test', function(){ // Make your changes here
        var id = $(this).attr('id');
        console.log("clicked" + id);
    });

    generatePage();
});

According to the jquery documentation .on accepts the following parameters:

.on( events [, selector] [, data], handler(eventObject) )

Including selector is described as follows:

When a selector is provided, the event handler is referred to as delegated. The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector. jQuery bubbles the event from the event target up to the element where the handler is attached (i.e., innermost to outermost element) and runs the handler for any elements along that path matching the selector.



来源:https://stackoverflow.com/questions/10371677/how-to-attach-jquery-event-handlers-for-newly-injected-html

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