繁体   English   中英

为多个同名类抓取浮点值

[英]Scraping float values for multiple classes of the same name

我正在尝试将相同的数学更改应用于 6 个不同跨度中的 6 个不同数字,这些数字都共享同一类。 使用此 HTML:

<span class="PageText_L483n">$8.00</span>
<span class="PageText_L483n">$9.00</span>
<span class="PageText_L483n">$10.00</span>
<span class="PageText_L483n">$11.00</span>
<span class="PageText_L483n">$12.00</span>
<span class="PageText_L483n">$13.00</span>

我最初有这个JS:

$(function() {
       var price = parseFloat($('.PageText_L483n').text().substr(1));
       var discount = price * 0.2;
       var newPrice = price - discount;
       var newText = '<div>$' + price + '</div> $' + newPrice;
       $('.PageText_L483n').html(newText);
       $('.PageText_L483n div').css("text-decoration", "line-through");

});

但这只会用第一个跨度的信息替换所有跨度。 然后我尝试在这个 JS 中使用数组:

$(function() {

       var prices = [];
       for (var i = 0; i < 6; i++) {
           prices[i] = parseFloat($('.PageText_L483n:nth-of-type(i+1)').text().trim().substr(1));
       }
       for (var j = 0; j < 6; j++) {
            var discount = prices[j] * 0.2;
            var newPrice = prices[j] - discount;
            var newText = '<div>$' + prices[j] + '</div> $' + newPrice;
            $('.PageText_L483n').html(newText);
            $('.PageText_L483n div').css("text-decoration", "line-through");
       }

});

但现在它什么都不做。 有人能指出我正确的方向吗?

JSFiddle: http : //jsfiddle.net/vSePd/

小提琴

由于您使用的是 jQuery,您可以轻松地遍历元素本身:

$(function() {

    $('span.PageText_L483n').each(function() {
        var span = $(this);
        var price = parseFloat(span.text().substring(1));
        var discount = price * 0.2;
        var newPrice = price - discount;
        span.html('<div style=text-decoration:line-through>$' + price.toFixed(2) + '</div> $' + newPrice.toFixed(2));
    });

});

如果您出于任何原因不想使用 jQuery:

$(function() {
    var spans = document.querySelectorAll('span.PageText_L483n');

    for ( var i = 0, l = spans.length; i < l; ++i ) {
        var price =  parseFloat(spans[i].textContent.substring(1));
        var discount = price * 0.2;
        var newPrice = price - discount;
        spans[i].innerHTML = '<div style=text-decoration:line-through>$' + price.toFixed(2) + '</div> $' + newPrice.toFixed(2);
    }
});

正如 kalley 所说明的,jQuery 的.each()将是一个合适的函数,可以在对匹配选择器的一组元素执行操作时使用。

$('.PageText_L483n')破坏你的代码的原因是它总是选择你的所有span 因此,例如,当使用$('.PageText_L483n').html(newText)html()函数将应用于与选择器匹配的所有元素。

使用each() ,您可以访问$(this) ,它基本上指向函数当前循环遍历的所有匹配元素中的一个元素,这允许您在每次运行期间执行单独的操作。

$(jquery).each();

看看这个: http : //jsfiddle.net/vSePd/3/

你是这个意思吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM