我有一個我正在嘗試處理的代碼示例,但每個尺寸的價格會輸出不同的內容。例如,小號為 20 歐元,中號:30 歐元,大號:40 歐元。
我想要做的是每次在頁面上選擇不同的尺寸時獲取價格。我正在使用 MutationObserver 來觀察價格的變化。但是,當我在我的原始代碼中使用 console.log 或嘗試將其添加到新類 newPrice 中時,我只能得到第一個價格大小,即 20 歐元,我不知道如何解決這個問題。任何有關我如何解決此問題的幫助或指導將不勝感激。
var targetNode = document.querySelector('.productDetails');
var price = document.querySelector('.productPrice');
var config = { childList: true };
var callback = function(mutationsList, observer) {
for(var mutation of mutationsList) {
if (mutation.type == 'childList') {
console.log(price.innerHTML);
}
}
};
var observer = new MutationObserver(callback);
observer.observe(targetNode, config);
var clickSize = document.querySelectorAll('.sizeContainer li');
clickSize.forEach( function (el) {
el.addEventListener('click',function() {
var node = document.querySelector('.newPrice').insertAdjacentHTML("afterbegin", " " price.innerHTML " ");
});
});
<div class="productDetails">
<ul class="sizeContainer">
<li>Small</li>
<li>Medium</li>
<li>Large</li>
</ul>
<p class="productPrice"> Price of the product would be output here</p>
<p class="newPrice"></p>
</div>
uj5u.com熱心網友回復:
我已經設法使用 .textContent 而不是使用 innerHTML 來定位我想要獲得的值,以及其他一些調整。將我的答案留在這里,因為它可能/可能對其他人沒有用。
var targetNode = document.querySelector('.productDetails .productPrice');
var config = {
characterData: false,
attributes: false,
childList: true,
subtree: false
};
var callback = function(mutationsList, observer) {
for (var mutation of mutationsList) {
if (mutation.type == 'childList') {
window.console.log(targetNode.textContent);
}
}
};
var observer = new MutationObserver(callback);
observer.observe(targetNode, config);
var clickSize = document.querySelectorAll('.sizeContainer li');
clickSize.forEach( function (el) {
el.addEventListener('click',function() {
var node = document.querySelector('.newPrice');
node.innerHTML = "" targetNode.textContent "";
});
});
<div class="productDetails">
<ul class="sizeContainer">
<li>Small</li>
<li>Medium</li>
<li>Large</li>
</ul>
<p class="productPrice"> Price of the product would be output here</p>
<p class="newPrice"></p>
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/376352.html
標籤:javascript dom 节点 突变观察者 内容观察者
下一篇:使用輸出引數進行Oracle呼叫的Dapper給出了“PL/SQL:數字或值錯誤:DML回傳:寫入主機變數時出錯”
