jQuery 无法使用 .on() 将事件绑定到 AJAX 加载的元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8343991/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 10:23:50  来源:igfitidea点击:

jQuery can't bind event to AJAX loaded element using .on()

eventsjquerybindingjavascript-events

提问by CodeVirtuoso

Using .load, I'm loading the following content into #step_2 div:

使用 .load,我将以下内容加载到 #step_2 div:

<div id="step_2">
    Select a subcategory:
    <select id="subcategory_id" name="subcategory_id">
        <option value="0">All subcategories</option>
        <option value="68">Cool</option>
        <option value="15">Cooler</option>
        <option value="74">Excellent</option>
    </select>
</div>

I'm then trying to detect when user selects something:

然后我试图检测用户何时选择某些内容:

$("#subcategory_id").on("change", function(){
    alert( 'Success!' );
});

but with no success. Does anyone see what I'm doing wrong? Help greatly appreciated.

但没有成功。有没有人看到我做错了什么?非常感谢帮助。

NOTES:

笔记:

Here's the full CSS path as seen by FireBug:

这是 FireBug 看到的完整 CSS 路径:

html.js body div#container div#main form div#step_2 select#subcategory_id

Here's the full javascript file, if context matters:

这是完整的 javascript 文件,如果上下文很重要:

$(document).ready(function() {

    $("#category_id").change(function() {
        $("#spinner").show();
        $("#step_2").load("process.php?selected=category", { value: $(this).val() }, function() {
            // Do something to say the data has loaded sucessfully
            $("#spinner").hide();
        });
    });

    $("#subcategory_id").on("change", function(){
        alert( 'Success!' );
    });

});

回答by Richard Dalton

In this case you need to use onin a similar way to delegate, the syntax you are using is the replacement for bind.

在这种情况下,您需要以on与 类似的方式使用delegate,您使用的语法是bind.

$("#step_2").on("change", "#subcategory_id", function(){
    alert( 'Success!' );
});

The first selector has to be an element that won't be replaced. This way, when the event bubbles up to this point it is caught. You then specify the actual element that will trigger the event as the 2nd parameter of .on.

第一个选择器必须是一个不会被替换的元素。这样,当事件冒泡到这一点时,它就会被捕获。然后指定将触发事件的实际元素作为 的第二个参数.on

回答by Dan Herbert

on(...)won't subscribe to events that aren't on the page yet without the proper setup. To do what you want, you should try the following:

on(...)如果没有正确设置,将不会订阅不在页面上的事件。要执行您想要的操作,您应该尝试以下操作:

$(document).on("change", "#subcategory_id", function(){
    alert( 'Success!' );
});

To make this more efficient, you should replace $(document)with the closest parent of the element that you know will be on the page when this code is called.

为了使这更有效,您应该替换$(document)为调用此代码时您知道将在页面上的元素的最接近的父元素。

回答by Tetaxa

You have to bind the handler after you've loaded the html, or use

您必须在加载 html 后绑定处理程序,或者使用

$("#step_2").on("change", "#subcategory_id", function(){
    alert( 'Success!' );
});

回答by Kevin B

Sure it can,

当然可以,

$(document).on("change", "#subcategory_id", function(){...});

To delegate events using .on, provide a parent element to bind to, and then the selector to delegate to.

要使用 .on 委托事件,请提供要绑定到的父元素,然后是要委托到的选择器。

回答by jValdron

You have to set the event after that you have loaded the new element. As AJAX is asynchronous, you need to have a callback in your load.

您必须在加载新元素之后设置事件。由于 AJAX 是异步的,你需要在你的负载中有一个回调。

$(document).ready(function() {

    $("#category_id").change(function() {
        $("#spinner").show();
        $("#step_2").load("process.php?selected=category", { value: $(this).val() }, 
        function() {
        // Do something to say the data has loaded sucessfully
            $("#spinner").hide();

            $("#subcategory_id").on("change", function(){
                alert( 'Success!' );
            });

        });
    });

});