jQuery无法识别由.html()方法创建的选择器

jQuery not recognizing selectors created by the .html() method

本文关键字:方法 创建 选择器 html 识别 jQuery      更新时间:2023-09-26

我正在尝试创建一个动态内容框。当我点击一个按钮时,框的内容会随着.html()而改变。当我点击另一个按钮后,内容会再次改变。

这很好,但在此框中创建的任何内容似乎都是不可选择的。

例如:

$(document).ready(function(){
    boxContent1 = "<div class='studySelector'></div>";
    $("#caseStudy").on('click',function(){
        $("#botBox").hide().html(caseStudy).fadeIn(1000);
    });
});

在这种情况下,#botBox的内容变化很好。然而,当我尝试与交互时

$(".studySelector").on('click',function(){
    alert("testing!");
});

什么也没发生。为什么会发生这种情况?

渲染后在dom中动态创建节点时,必须使用事件委派:

$('#botBox').on('click', '.studySelector',function(){
    alert("testing!");
});

应该起作用。