浮云間
2023-12-14 14:21:02
我在 Shopify 中有一個彈出模式,出于安全考慮,我使用文本節點而不是innerHtml。但是,每次我打開彈出模式時,文本節點都會不斷附加到我的 h1 標記中。有沒有辦法檢查節點是否已經被附加?(我不想使用布爾值來檢查是否已附加文本節點)html:<h1 id="ProductHeading" class="product__title product__title--template"></h1><h2 id="ProductHeadingModal" class="product__title product__title--template product__title--modal"></h2>javascript:var title = document.createTextNode(product.title);// Product heading is an element with h1 tagvar productHeading = document.getElementById("ProductHeading"); if(// how to check if element has no node?) { productHeading.appendChild(title);}整個 JavaScript 塊:window.onload = () => { if (window.__shgProductInits.length) { window.__shgProductInits.forEach((ele) => { let proId = document.getElementById(ele.uuid); proId.setAttribute('url', ele.productHandle); proId.style.cursor='pointer'; proId.addEventListener('click', (e) => { let productHandle = e.target.parentElement.parentElement.parentElement.getAttribute('url'); fetch('/products/'+productHandle+'.js') .then((res) =>{return res.json()}) .then((product) => { console.log(product) var product = product; document.getElementsByClassName("product-modal")[0].style.display = "block"; var title = document.createTextNode(product.title); var productHeading = document.getElementById("ProductHeading"); var productHeadingModal = document.getElementById("ProductHeadingModal"); if(!(productHeading.hasChildNodes())) { productHeading.appendChild(title); productHeadingModal.appendChild(title); var price = document.createTextNode("$" + parseInt(product.price).toFixed(2)); document.getElementById("product-price").appendChild(price); } }); }); }); }ProductHeading 本身不是一個節點(我認為)。檢查innerHtml的長度不起作用,因為它總是0
2 回答

繁星coding
TA貢獻1797條經驗 獲得超4個贊
有幾種方法:
if (element.firstChild) {
? ? // It has at least one
}
或hasChildNodes()函數:
if (element.hasChildNodes()) {
? ? // It has at least one
}
或childNodes 的length 屬性:
if (element.childNodes.length > 0) { // Or just `if (element.childNodes.length)`
? ? // It has at least one
}
所以你可以這樣寫
var title = document.createTextNode(product.title);
// Product heading is an element with h1 tag
var productHeading = document.getElementById("ProductHeading");?
if(!(productHeading.hasChildNodes())) {
? productHeading.appendChild(title);
}
添加回答
舉報
0/150
提交
取消