gpt4 book ai didi

jquery - 从具有相同类的 span 中获取文本

转载 作者:行者123 更新时间:2023-12-01 08:35:54 24 4
gpt4 key购买 nike

我有 5 个跨度,可能更多,全部共享类 .price

阅读Jquery的文档,我发现最好的方法是使用map函数。像这样:

var prices = $(".price")
.map(function () {
return this.text;
}).get().join();

I need a list of prices, So afterwards I can do something like (notice the minus 20 part):

$('.price').text(function (index) {
return "S/ " + prices[index]-20;
});

但是当我提醒价格时,我得到一个空窗口。

html:

<span class="price price_50">50</span>
<span class="price price_100">90</span>
<span class="price price_200">120</span>
<span class="price price_300">140</span>
<span class="price price_500">150</span>

最佳答案

内部 map this引用DOM并且它没有任何text属性。因此将其转换为 jQuery 对象并使用 text() 方法获取文本内容或从 DOM 对象获取 textContent 属性。

var prices = $(".price")
.map(function() {
return $(this).text();
}).get().join();

console.log(prices)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<span class="price price_50">1</span>
<span class="price price_100">2</span>
<span class="price price_200">3</span>
<span class="price price_300">4</span>
<span class="price price_500">5</span>

关于jquery - 从具有相同类的 span 中获取文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55658560/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com