gpt4 book ai didi

javascript - 使用jq通过html()或append()将html注入(inject)到另一个元素注入(inject)的元素不能被jq访问但使用JS它可以工作吗?

转载 作者:行者123 更新时间:2023-11-28 15:31:49 25 4
gpt4 key购买 nike

这是我的代码:

//This works
$("#addNew").click(function(){
$("#Q_countainer").append("<img class='MyClassName' src='0369.png' >");
});
//This doesn't work
$(".MyClassName").click(function(){
alert("HERE")
});
//This doesn't work either
$(document).on("click",".MyClassName",function(){
alert("HERE")
});

第一部分在 id="Q_counttainer" 的元素内添加图像。第二和第三部分无法通过类、id、名称或任何内容检测 img

最佳答案

//This works
$("#addNew").click(function(){
//This does work, but...
$('<img class="MyClassName" src="0369.png">')
.appendTo($("#Q_countainer"))
.click(function(){
alert("HERE 1");
});
});

// ... this is better (this will work only *after* #addNew will have been clicked)
// This is called delegated events and is a good practice.
$(document).on("click",".MyClassName",function(){
alert("HERE 2");
});

这是一个JSFiddle demo

关于javascript - 使用jq通过html()或append()将html注入(inject)到另一个元素注入(inject)的元素不能被jq访问但使用JS它可以工作吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26995396/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com