簡體   English   中英

如何從其他HTML文件中選擇元素

[英]How can I select elements from my other html files

原諒我的無知,我是Web開發的新手,我有一個簡單的預算應用程序,可以從用戶那里獲取信息。 我想在另一個HTML頁面中顯示此信息。 但是,當我嘗試選擇特定的dom元素時,會拋出一個找不到它的錯誤。

我以為我的問題可以用webpack解決。 我將所有js文件捆綁在一起,並提供給我的所有html頁面,但仍然無法訪問我的元素。

//My controller got the data from the user and created an instance of the Budget object and gave the information to my displayincome function.

displayIncome(newBudget.id, newBudget.date, newBudget.description, newBudget.value);

//my displayIncome then tries to insert this data to the .item-container div.

export const displayIncome = (id, date, description, value) => {
  const markup = `
           <div class="item" href="#${id}">
            <div class= "item__date">
              ${date}
            </div>
            <div class="item__description">
              ${description}
            </div>
            <div class="item__value">
              ${value}
              <div class="item__delete">
                <div class="item__delete--btn"><i class="far fa-trash-alt"></i>
                </div>
              </div>
            </div>
        `;
  document.querySelector('.item-container').insertAdjacentHTML('afterend', markup);
};

預計將信息插入div。 實際結果得到我這個錯誤:

bundle.51d4e9d….js:1未捕獲的TypeError:無法讀取HTMLDivElement.document.querySelector.addEventListener處bundle.51d4e9d….js:1處c(bundle.51d4e9d….js:1)處為null的屬性'insertAdjacentHTML'。 e(bundle.51d4e9d….js:1)

確保在元素.item-container之后包含bundle.js或在事件“ DOMContentLoaded”之后使用它。

例:

document.addEventListener("DOMContentLoaded", function () {
   displayIncome(newBudget.id, newBudget.date, newBudget.description, newBudget.value);
});

在代碼初始化之前使用displayIncome還有另一個問題。

暫無
暫無

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

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