【问题标题】:Getting value of different selections in Javascript在Javascript中获取不同选择的价值
【发布时间】:2026-01-22 00:05:01
【问题描述】:

我在下面有一个我正在尝试处理的代码示例,除了每种尺寸的价格会输出不同的东西。例如,小号 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>

【问题讨论】:

    标签: javascript dom nodes mutation-observers contentobserver


    【解决方案1】:

    我已经设法使用 .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>

    【讨论】:

      最近更新 更多