如何从NodeList中选取元素并修改select内price span的内容?
问题
页面中有一个id为movie的select组件,其option标签内包含class为price的span元素,尝试修改该span的内容时始终显示为空,且forEach循环中的console.log也无输出。如何正确访问moviePrice的每个元素并修改其值?
代码示例:
const moviePrice = document.querySelectorAll('.price'); function convertCurrency() { const currency_one = currency.value; const amountMovie = movieSelect.value; fetch(`https://v6.exchangerate-api.com/v6/latest/USD`) .then(res => res.json()) .then(data => { const rate = data.conversion_rates[currency_one]; const ratedPrice = (amountMovie * rate).toFixed(2); currencyTotal.innerText = currency_one; moviePrice.forEach(element => { element.innerText = ratedPrice + ' ' + currency_one; console.log(element); //This is not showing in the console }); ticketPrice = ratedPrice; }) .catch(error => { console.error('Error en la conversión de moneda:', error); }) }
<select id="movie" autocomplete="off"> <option value="10">Avengers: Endgame <span class="price"></span></option> <option value="12">Joker <span class="price"></span></option> <option value="8">Toy Story 4 <span class="price"></span></option> <option value="9">The Lion King <span class="price"></span></option> </select>
解决方法
问题核心是浏览器对select内部option元素的DOM解析限制:绝大多数浏览器不会渲染option标签内的子元素(比如你嵌套的span),直接用querySelectorAll('.price')根本拿不到任何节点,所以moviePrice是空的NodeList,forEach自然不会执行。
下面是两种可行的修正方案:
方案一:直接修改option的文本内容(无需嵌套span)
去掉option里的span标签,直接基于option的value值计算后重写文本:
<select id="movie" autocomplete="off"> <option value="10">Avengers: Endgame</option> <option value="12">Joker</option> <option value="8">Toy Story 4</option> <option value="9">The Lion King</option> </select>
对应的JavaScript调整:
const movieSelect = document.getElementById('movie'); function convertCurrency() { const currency_one = currency.value; fetch(`https://v6.exchangerate-api.com/v6/latest/USD`) .then(res => res.json()) .then(data => { const rate = data.conversion_rates[currency_one]; // 遍历所有option元素 Array.from(movieSelect.options).forEach(option => { const basePrice = parseFloat(option.value); const ratedPrice = (basePrice * rate).toFixed(2); // 拼接原始电影名和转换后的价格 option.textContent = `${option.textContent} ${ratedPrice} ${currency_one}`; }); ticketPrice = ratedPrice; }) .catch(error => { console.error('Error en la conversión de moneda:', error); }) }
方案二:用data属性存储原始电影名(避免文本拆分出错)
如果担心后续修改文本时拆分出错,可以给每个option加data-title属性保存原始名称:
<select id="movie" autocomplete="off"> <option value="10" data-title="Avengers: Endgame">Avengers: Endgame</option> <option value="12" data-title="Joker">Joker</option> <option value="8" data-title="Toy Story 4">Toy Story 4</option> <option value="9" data-title="The Lion King">The Lion King</option> </select>
JavaScript部分调整:
Array.from(movieSelect.options).forEach(option => { const basePrice = parseFloat(option.value); const ratedPrice = (basePrice * rate).toFixed(2); // 从data属性取原始名称,拼接价格 option.textContent = `${option.dataset.title} ${ratedPrice} ${currency_one}`; });
内容的提问来源于stack exchange,提问作者Lienigena
相关产品推荐
相关产品推荐

