如何在 jQuery .load() 之后更新 DOM?

How to update the DOM after jQuery .load()?

我想从模板文件 (b.xhtml) 加载 html 内容,将其插入调用文件 (a.xhtml),然后更新插入的节点(例如add/delete 属性等)。

插入部分工作正常,但 DOM 似乎没有更新。

这是测试用例。

a.xhtml(调用html文件)

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("button").click(function(){
                $("#placeholder").load("b.xhtml #id2");
                // why doesn't this work?
                var myTemp = document.querySelector("#id2");
                if (myTemp) {
                    alert(myTemp.innerHTML);
                } else {
                    alert("#id2 is undefined");
                };
            });
        });
    </script>
</head>
<body>
    <h1>jQuery load test</h1>
    <div><button>Load template</button></div>
    <div id="placeholder"></div>
</body>
</html>

b.xhtml(模板html文件)

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
    <div id="templates">
        <p id="id1">This is template one</p>
        <p id="id2">This is template two</p>
    </div>
</body>
</html>
  1. 如何在 .load() 之后更新 DOM?
  2. 是否有更简单的方法从外部 HTML 文件插入 HTML 节点,该文件会自动更新 DOM?
  3. 或者,如何在 b.xhtml 节点插入 a.xhtml 之前(或之后)更改或添加该节点的属性?例如,我如何将 alt="template text" 属性添加到 #id2 节点?

.load() 方法是异步的,因此您的脚本正在执行该行,但不会等待它完成后再继续下一行。你可以做几件事。首先,使用回调函数:

$("#placeholder").load("b.xhtml #id2", function(){
            var myTemp = document.querySelector("#id2");
            if (myTemp) {
                alert(myTemp.innerHTML);
            } else {
                alert("#id2 is undefined");
            };
});

或者,使用 .done():

$("#placeholder").load("b.xhtml #id2").done(function(){
            var myTemp = document.querySelector("#id2");
            if (myTemp) {
                alert(myTemp.innerHTML);
            } else {
                alert("#id2 is undefined");
            };
});

尝试这样做:

    <script>
        $(document).ready(function(){
            $("button").click(function(){
                $("#placeholder").load("b.xhtml #id2",function()
                {
                    var myTemp = document.querySelector("#id2");
                    if (myTemp) {
                      alert(myTemp.innerHTML);
                    } else {
                      alert("#id2 is undefined");
                    };
                });
            });
        });
    </script>