如何使用 DOMNodeInsert 将项目插入到 DOM 中

How to get the items inserted in the DOM using DOMNodeInserted

本文关键字:DOM 插入 项目 何使用 DOMNodeInsert      更新时间:2023-09-26

我想使用 DOMNodeInsert 获取动态生成的 DOM 中的项目值。这是我的代码。@I想要获取值的项目是 li 例如

<div id="demo">    
    <ul>
        <li class="req">Chemistry</li>
        <li class="req">English</li>
        <li class="req">Maths</li>
    </ul>
</div>

这是代码

$('#demo').on('DOMNodeInserted', function(e) {
    var that = $(this);
    if ($(e.target).is('.req')) {
        alert(oneoftheitemsintheli);
    }
});

我想继续li中的项目,例如MathsChemistry等。我需要知道如何获得这些物品。谢谢

给定每个li都有类req,您可以使用each来迭代它们并获取文本值 - 或您需要的任何其他属性。

$('#demo').on('DOMNodeInserted', function(e) {
    $('.req').each(function() {
        alert($(this).text());
    });
});

示例小提琴