簡體   English   中英

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

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

我想從模板文件(b.xhtml)加載html內容,將其插入調用文件(a.xhtml),然后更新插入的節點(例如添加/刪除屬性等)。

插入部分工作正常,但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. 或者,如何在插入a.xhtml之前(或之后)更改或添加b.xhtml節點的屬性? 例如,如何在#id2節點中添加alt =“模板文本”屬性?

.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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM