为具有相同名称的多个类报废浮点值

Scraping float values for multiple classes of the same name

本文关键字:      更新时间:2023-09-26

我正在尝试将相同的数学变化应用于共享同一类的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/

Fiddle

由于您使用的是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 s的所有。因此,例如,当使用$('.PageText_L483n').html(newText)时,html()函数将应用于与选择器匹配的所有元素。

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

$(jquery).each();

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

你是这个意思吗?

相关文章:
  • 没有找到相关文章