突变操作器无法与深嵌套元素一起工作

发布于 2025-01-23 18:14:13 字数 1287 浏览 0 评论 0原文

我想观察一个深度嵌套的元素(在此示例中的TextArea),但是以下代码不起作用。

谁能帮我吗?

<div id="parent" style="width:500px;height:200px;" class="parent mother">

</div>
<button id="button" style="width:200px;height:60px;" class="button btn"></button>
<script>
    button = document.getElementById("button");
    const observer = new MutationObserver(function(mutations_list) {
        mutations_list.forEach(function(mutation) {
            mutation.addedNodes.forEach(function(added_node) {
                if (added_node.className == 's-JGcg fFOiLQ JhFYDw T9BsEA _01h2nw') {
                    //if (added_node.id == 'child') {
                    console.log(`${added_node}has been added`);

                    observer.disconnect();
                }
            });
        });
    });

    observer.observe(document.querySelector("body"), {
        subtree: true,
        childList: true,
    });

    button.addEventListener("click", fn);

    function fn() {
        document.querySelector("#parent").innerHTML = `<div><div><div>
            <textarea class="s-JGcg fFOiLQ JhFYDw T9BsEA _01h2nw" placeholder="What happens" rows="5"></textarea>
            </div></div></div>`;
    }
</script>

I want to observer a deeply nested element (textarea in this example), but the following code does not work.

can anyone help me out?

<div id="parent" style="width:500px;height:200px;" class="parent mother">

</div>
<button id="button" style="width:200px;height:60px;" class="button btn"></button>
<script>
    button = document.getElementById("button");
    const observer = new MutationObserver(function(mutations_list) {
        mutations_list.forEach(function(mutation) {
            mutation.addedNodes.forEach(function(added_node) {
                if (added_node.className == 's-JGcg fFOiLQ JhFYDw T9BsEA _01h2nw') {
                    //if (added_node.id == 'child') {
                    console.log(`${added_node}has been added`);

                    observer.disconnect();
                }
            });
        });
    });

    observer.observe(document.querySelector("body"), {
        subtree: true,
        childList: true,
    });

    button.addEventListener("click", fn);

    function fn() {
        document.querySelector("#parent").innerHTML = `<div><div><div>
            <textarea class="s-JGcg fFOiLQ JhFYDw T9BsEA _01h2nw" placeholder="What happens" rows="5"></textarea>
            </div></div></div>`;
    }
</script>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文