簡體   English   中英

Javascript 看不到從本地文件中提取的 html 元素

[英]Javascript can't see html elements fetched form a local file

我有一個通過將 Word 文件轉換為 html 創建的 html 文件。 我將 Word 生成的 html 代碼復制粘貼到我添加到項目中的 html 文件中(我們稱之為“local.html”)。

通過使用 fetch() function,我從 local.html 文件中檢索了文本,並將數據(格式化為文本)添加到我的 index.ZFC35FDC70D5FC69D2698Z83A82 中 div 的 innerHTML

執行此操作的 js 代碼是:

 fetch("./local.html")
  .then(response => {
    return response.text();
  })
  .then(data => {
    document.getElementById("aDivInIndexhtml").innerHTML = data;
  });

Word生成的html標簽被瀏覽器識別並正確呈現(我使用的是Opera)。

但是,javascript 沒有看到這些元素(我對它們無能為力)。

我認為這是因為我將它們添加到 innerHTML 而不是將元素附加到 DOM。

因此,我嘗試將包含這些元素的 div(“aDivInIndexhtml”)append 到我的 index.html 中的另一個 div。 同樣的問題。 代碼是:

   var newDiv = document.createElement("div");
   newDiv.appendChild("aDivInIndexhtml");

最奇怪的是當我這樣做時:

console.log(document.getElementById("aDivInIndexhtml").children;

我得到一個列出這些元素的 HTMLCollection。

但是,如果我嘗試使用例如訪問集合中的任何元素:

document.getElementById("aDivInIndexhtml").children[0];`

或者

 document.getElementById("aDivInIndexhtml").children.item(0);

我收到一條錯誤消息,提示它未定義。

如果我做:

document.getElementById("aDivInIndexhtml").children.length

我得到一個長度為 0 的集合,盡管在 console.loged 時同一個集合顯示了許多元素!

所有元素都出現在瀏覽器的 DOM 中並被渲染,但對於 javascript 或 jquery,它們幾乎不存在。

我認為這將是我的代碼在 js 文件中的位置。 我把它移到了最后。 同樣的問題。

它是否鏈接到 Word 生成的 html/xml 結構? 如果是這樣,如何解決?

打印時

document.getElementById("aDivInIndexhtml").children[0];

和這個

 document.getElementById("aDivInIndexhtml").children.item(0);

你得到未定義只是因為你的 div 元素 aDivInIndexhtml 還沒有任何子元素並且它是一個數組,所以這就是它返回長度 0 的原因,因為它是空的。 所以要完成它,只需像這樣在 aDivInIndexhtml div 中的 append 孩子:

改變這個

   var newDiv = document.createElement("div");
   newDiv.appendChild("aDivInIndexhtml");

至此

   var newDiv = document.createElement("div");
   var aDivInIndexhtml = document.getElementById("aDivInIndexhtml");
   newDiv.appendChild(aDivInIndexhtml);

這里還有一件事是錯誤的,你在 appendChild 方法中傳遞了字符串“aDivInIndexhtml”,這是元素不在 DOM 中呈現的另一個原因,因為 appendChild 方法需要元素而不是字符串。

暫無
暫無

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

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