所以我沒有這個問題的代碼,但我很想知道我是否想創建一個 li 的 ul 并想添加和洗掉 li,我知道 li 的數量是動態的。那么如何在添加或洗掉時獲取 li (陣列索引)的數量。我試過做 const len = document.querySelectorAll("li") 這只會回傳靜態陣列的長度,如果我添加或洗掉 li 它不會改變陣列的長度
uj5u.com熱心網友回復:
document.getElementsByTagName("li")回傳一個實時的 HTMLCollection,因此它的長度應該始終是最新的。
https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName
uj5u.com熱心網友回復:
$("#id li").length
會給你計數。
uj5u.com熱心網友回復:
您可以嘗試獲取父元素并檢查childElementCount屬性:
const len = document.querySelector("ul").childElementCount;
請注意,每次添加或洗掉<li>. 該len變數將是執行代碼時元素的數量。
這也是您的代碼所發生的情況,如果您添加/洗掉一個<li>然后重做代碼,數字會改變:
// Let's imagine you have 3 <li> inside a <ul>.
const len = document.querySelectorAll("li");
alert(len); // will print 3
// Creating the new <li> element..
const newLi = document.createElement("li");
newLi.appendChild(document.createTextNode("I am new!"));
// ..and adding it to the <ul>
document.querySelector("ul").appendChild(newLi);
// Can't use "len" again here since it's a constant
const len2 = document.querySelectorAll("li");
alert(len2); // will print 4
alert(len); // will still print 3
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/479009.html
標籤:javascript html 列表
