如何将弹出窗口添加到动态创建的列表项

How to add popover to dynamically created list items

我有以下代码。单击现有列表项会显示弹出框。

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Test</title>

    <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        $(function () {
            $('[data-toggle="popover"]').popover()
        })
    </script>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.0/dist/css/bootstrap.min.css"/>
</head>

<body>
    <div class="container">
        <div class="card" style="width: 18rem;">
            <div class="card-header">
                Featured
            </div>
            <ul id="card-list" class="list-group list-group-flush">
                <li id="card-item" class="list-group-item" data-toggle="popover" title="Rule Details" data-placement="top" data-html="true" data-content="&lt;h3&gt;Popover Content&lt;/h3&gt;">Cras justo odio</li>
            </ul>
        </div></br>
        <button id="test" type="button" class="btn btn-outline-dark btn-sm">Test</button>
    </div>
</body>

</html>

上面的代码有一个测试按钮,用于将项目添加到当前列表。我使用下面的代码定义新项目,在此期间我设置了弹出框属性。可以添加新列表项,但单击它们不会弹出弹出窗口。请帮忙!

let listItem = document.createElement('li');
listItem.innerHTML = "Test";
listItem.className = "list-group-item";
listItem.setAttribute("data-toggle", "popover");
listItem.setAttribute("title", "Rule Details");
listItem.setAttribute("data-placement", "top");
listItem.setAttribute("data-html", "true");
listItem.setAttribute("data-content", "<strong>test Hello World</strong>");
document.getElementById("card-list").appendChild(listItem);

您必须在新创建的元素上初始化弹出框。由于 popover 是一个 jQuery 插件,请将您的元素转换为 jQuery 对象并在附加之前应用 popoper,例如:

let listItem = document.createElement('li');
listItem.innerHTML = "Test";
listItem.className = "list-group-item";
listItem.setAttribute("data-toggle", "popover");
listItem.setAttribute("title", "Rule Details");
listItem.setAttribute("data-placement", "top");
listItem.setAttribute("data-html", "true");
listItem.setAttribute("data-content", "<strong>test Hello World</strong>");
listItem = $(listItem);
listItem.popover();
$("#card-list").append(listItem);