繁体   English   中英

在Jquery中使用动态加载的html类

[英]Use classes of dynamically loaded html with Jquery

我有一个动态加载的页面,其中包含类产品的div。 jQuery在以下代码中看不到此类。 当我单击产品div时,它什么也没做。 但是,在nav-element上的clicli效果很好。 有什么办法使其兼容吗?

$(document).ready(function(){
$(".nav-element").click(function(){
    var id = $(this).attr('id');
    alert(id);
    $(".nav-element").css("background", "#fff");
    $("#"+id).css("background", "#A4CFBE");
    $(".content-white").load(id+".html");
    });
    $(".content-white").load("nav-element1.html");
$(".product").click(function(){
    alert("poop");
})
}); 

具有类产品div的动态加载页面

您需要使用事件委托 您必须使用.on()使用委托事件方法。

$(document).on('event','selector',callback_function)

理想情况下,应使用最近的静态容器替换document 这里是".content-white"

$(".content-white").on('click', '.product', function () {
    alert("poop");
});

尝试委托事件处理程序

$(document).ready(function () {
    $(".nav-element").click(function () {
        var id = $(this).attr('id');
        alert(id);
        $(".nav-element").css("background", "#fff");
        $("#" + id).css("background", "#A4CFBE");
        $(".content-white").load(id + ".html");
    });
    $(".content-white").load("nav-element1.html");

    // event delegation to the closest static element
    $(".content-white").on('click', ".product", function () {
        alert("poop");
    });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM