如何为新注入的html附加jquery事件处理程序? [英] how to attach jquery event handlers for newly injected html?

查看:102
本文介绍了如何为新注入的html附加jquery事件处理程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果HTML尚未生成,我将如何使用 .on()? jQuery页面说

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

如果新的HTML被注入到页面中,则在新的HTML放入页面后选择元素并附加事件处理程序。
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?

所以如果我有

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

其中,generatePage()创建了一堆具有 .test ,我如何重新绑定 .on()

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.

推荐答案

下面。人们可以假定身体标签总是可用的,所以将事件处理程序附加到身体是安全的,并将事件委托给选择器,在这种情况下 .test

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();
});

或者如果 generatePage()也生成html,head和body

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();
});

根据 jquery文档 .on接受以下参数:

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

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

包含选择器描述如下: / p>

Including selector is described as follows:


当提供选择器时,事件处理程序称为
委派。当事件直接发生在
绑定元素上时,处理程序不会被调用,但仅适用于
与选择器匹配的后代(内部元素)。 jQuery将事件从事件上升到
到处理器附加的元素(即最内层到
最外面的元素),并运行沿着
路径匹配选择器的任何元素的处理程序。

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.

这篇关于如何为新注入的html附加jquery事件处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆