如何用jQuery为含SHIRT/JACKET类的div内价格加15?
问题描述
现有如下HTML代码:
<div class="product BLACKSHIRT"> <span class="displayPrice">£50</span> </div> <div class="product WHITESHIRT"> <span class="displayPrice">£40</span> </div> <div class="product GREENSHIRT"> <span class="displayPrice">£55</span> </div> <div class="product YELLOWSHIRT"> <span class="displayPrice">£50</span> </div> <div class="product BLACKJACKET"> <span class="displayPrice">£60</span> </div> <div class="product WHITESHORTS"> <span class="displayPrice">£20</span> </div> <div class="product BLACKTROUSERS"> <span class="displayPrice">£30</span> </div>
需求如下:
- 筛选出类名包含
SHIRT或JACKET的<div>元素 - 提取这些元素内部
<span class="displayPrice">的价格值,去掉£符号转为数字后加15 - 将计算后的价格加回
£符号,更新回原标签
示例:
修改前:
<div class="product BLACKSHIRT"> <span class="displayPrice">£50</span> </div>
修改后:
<div class="product BLACKSHIRT"> <span class="displayPrice">£65</span> </div>
无法控制现有HTML结构,请问该需求能否实现?
解决方案
完全可以实现,用原生JavaScript就能搞定,不需要依赖任何框架,具体代码如下:
// 筛选出类名包含SHIRT或JACKET的div元素 const targetDivs = document.querySelectorAll('div.product[class*="SHIRT"], div.product[class*="JACKET"]'); // 遍历每个目标div targetDivs.forEach(div => { // 获取内部的displayPrice元素 const priceSpan = div.querySelector('.displayPrice'); if (!priceSpan) return; // 避免无该元素时出错 // 提取价格并计算新值 const originalPrice = priceSpan.textContent.replace('£', ''); const newPrice = parseInt(originalPrice, 10) + 15; // 更新回标签 priceSpan.textContent = `£${newPrice}`; });
代码说明:
document.querySelectorAll('div.product[class*="SHIRT"], div.product[class*="JACKET"]'):利用属性选择器[class*="XXX"]匹配类名含指定字符串的元素,同时限定product类确保只选中目标div- 遍历每个选中的div,定位内部的
displayPricespan标签 - 通过
replace去除£符号,转成整数后加15 - 将新价格拼接
£后更新回span的文本内容
这段代码可直接在浏览器控制台运行,或者放在页面脚本标签中(需确保DOM加载完成后执行,比如包裹在DOMContentLoaded事件回调里)。
内容的提问来源于stack exchange,提问作者Gary
相关产品推荐
相关产品推荐

