亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

檢查html標簽是否包含文本節點

檢查html標簽是否包含文本節點

浮云間 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);

}



查看完整回答
反對 回復 2023-12-14
?
慕的地10843

TA貢獻1785條經驗 獲得超8個贊

if (productHeading.hasChildNodes()) {

}


查看完整回答
反對 回復 2023-12-14
  • 2 回答
  • 0 關注
  • 176 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號