使用jQuery的。对不能绑定事件AJAX加载的元素() [英] jQuery can't bind event to AJAX loaded element using .on()

查看:191
本文介绍了使用jQuery的。对不能绑定事件AJAX加载的元素()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用.load

,我加载以下内容为#DIV step_2:

 < D​​IV ID =step_2>
    选择一个子分类:
    <选择一个id =subcategory_idNAME =subcategory_id>
        <期权价值=0>所有小类&L​​T; /选项>
        <期权价值=68>酷< /选项>
        <期权价值=15>冷却器和LT; /选项>
        <期权价值=74>优良< /选项>
    < /选择>
< / DIV>

我再努力,当用户选择的东西来检测:

  $(#subcategory_id)。在(变,函数(){
    警报('成功!');
});

但没有成功。有谁看到我在做什么错?大大有助于AP preciated

注:

下面是由萤火虫所看到完整的CSS路径:

  html.js体#DIV容器div#主要形式的div#step_2选择#subcategory_id

下面是完整的JavaScript文件,如果环境事项:

  $(文件)。就绪(函数(){    $(#CATEGORY_ID)。改变(函数(){
        $(#微调)显示()。
        $(#step_2)负荷(process.php选择=类别?{价值:$(本).VAL()},函数(){
            //做一些事情说数据已经成功地加载
            $(#微调),隐藏()。
        });
    });    $(#subcategory_id)。在(变,函数(){
        警报('成功!');
    });});


解决方案

在这种情况下,你需要以类似的方式使用委托,您正在使用的语法是用于替换绑定

  $(#step_2)。在(变,#subcategory_id功能(){
    警报('成功!');
});

第一选择器必须是不会被替换的元件。这样一来,当事件气泡直到该点它被捕获。然后,您指定将触发该事件为的。对第二个参数的实际元素。

Using .load, I'm loading the following content into #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:

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

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

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

});

解决方案

In this case you need to use on in a similar way to delegate, the syntax you are using is the replacement for 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.

这篇关于使用jQuery的。对不能绑定事件AJAX加载的元素()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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