gpt4 book ai didi

javascript - 如果 div 中的子元素在其 Id 中包含字符串,如何触发函数?

转载 作者:太空宇宙 更新时间:2023-11-04 09:53:01 26 4
gpt4 key购买 nike

每当某个子元素至少包含一个由函数指定的字符串时,我一直在尝试触发某种行为。我使用的代码是这样的:

<div id="myDIV" class="mystyle">
<script> /*some script goes here*/ </script>
<div id="asdkmasdp_123123">
<!--This DIV was created dynamically (not always) by the script before -->
Contingent DIV
</div>
</div>

<script>
function myFunction(){
if($("#myDIV").find("div[id*='masdp']").length)(function (){
alert("This works!");
});
}
myFunction();
</script>

如示例所述,子 DIV 并不总是存在(只有“脚本”存在)。当我希望它触发某些东西时,在本例中是浏览器警报。

我还没有找到正确的方法,因为我主要受限于当页面加载完成时子 DIV 不在 DOM 中,但仅在一些用户交互之后。

此外,子 DIV 的 ID 和类在每次创建时都不同。请注意,我无权访问创建此 DIV 的第 3 方 JS,只能访问其 #myDiv 容器。

最佳答案

您可以使用 MutationObserver 来观察 #myDiv 上的 subtreechildList 修改,并检查回调中的eeement:

// Set up the observer
var ob = new MutationObserver(function() {
// See if it exists now
if ($("#myDiv [id*='masdp']").length) {
console.log("Found it!");
}
});
ob.observe($("#myDiv")[0], {
childList: true,
subtree: true
});

// Randomly add the element later
setTimeout(function() {
$("#myDiv").append(
"<span id='masdpxxx'>masdp</span>"
);
}, Math.floor(Math.random() * 1000) + 200);
<div id="myDiv"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

关于javascript - 如果 div 中的子元素在其 Id 中包含字符串,如何触发函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38960930/

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