jQuery.text()获取html价格并用数字字段增加它

问题描述 投票:0回答:6

我怎样才能得到数字价格?简单的产品有:

<td class="wh-price">                           
   <span class="woocommerce-Price-amount amount"><span class="woocommerce-Price-currencySymbol">$</span>425.00</span>                       
</td>

批发产品有:

    <td class="wh-price">                           
        <del class="original-computed-price"><span class="woocommerce-Price-amount amount"><span class="woocommerce-Price-currencySymbol">$</span>625.00</span></del>

        <span style="display: block;" class="wholesale_price_container">
            <span class="wholesale_price_title"></span>
            <ins><span class="woocommerce-Price-amount amount"><span class="woocommerce-Price-currencySymbol">$</span>54,321.00</span></ins>
        </span>
    </td>

需要价格简单和批发(<ins>价格;而不是<del>价格)产品,所以当数量增加,我可以计算它们。

数量HTML:

    <td class="quantity-field">
        <div class="quantity">
            <input step="1" min="" max="" name="quantity" value="1" title="Qty" class="input-text qty text" size="4" pattern="[0-9]*" inputmode="numeric" type="number">
        </div>
    </td>

我试过这个jquery:

    $(document).ready(function(){
      $(".qty").on('change',function() {
        setPriceQ();
      });
    })
    const setPriceQ = function(){
      $.each(
        $('tr[data-role="product"]'),
        function(index,element){
          const $el = $(element);
          const originalPrice = $el.find('.woocommerce-Price-amount.amount').text();
          const totalQuantity = $el.find(".qty").val();            
          $el.find('#result').html( originalPrice * totalQuantity );
        }
      );
    };

但它没有工作,大部分时间显示$NaN所以我尝试了const originalPrice = parseInt($el.find('.woocommerce-Price-amount.amount').text(), 10);

还是行不通。在我的猜测.text()正在获得<span class="woocommerce-Price-currencySymbol">$</span>,这阻止了解析。

html代码是用php <?php echo $product->get_price_html() ?>生成的;对于简单的产品我只能通过使用<?php echo $product->get_price() ?>获得没有标记的数值,但对于批发产品价格,它不可能通过简单的PHP。

javascript php jquery html wordpress
6个回答
1
投票

我相信最好使用jquery和native函数的混合。 JQuery自动从结果集合中过滤掉文本节点,但是使用了

$el.find('.woocommerce-Price-amount.amount').get()[0].childNodes[1].textContent

您可以获取值的确切文本节点。 它支持所有货币,不需要更改标记。


1
投票

如果您愿意,可以使用.text()。replace(),但只有在您知道要尝试的货币符号时才能使用.replace()。

我会在价格附近添加一个<span data-role-price>425.00</span>然后选择它$el.find('[data-role-price]').text()

这只是我个人对如何解决问题的偏好,即使它增加了一些额外的HTML,好消息是它与货币无关。

如果您无法修改HTML,那么您可以执行此操作,这也是货币无关的

const currencySymbol = $el.find('.woocommerce-Price-currencySymbol');
const originalPriceWithSymbol = $el.find('.woocommerce-Price-amount.amount').text();
const originalPriceWithoutSymbol = originalPriceWithSymbol.replace(currencySymbol, '');

1
投票

你可以使用replace()函数这样做:

const originalPriceStr = $el.find('.woocommerce-Price-amount.amount').text().replace(/[$,]/g, ''));
const originalPrice = parseFloat(originalPriceStr, 10);

此外,您可能希望使用parseFloat,如果有美分,您不希望创建舍入错误。


1
投票

你可以使用.substring(1)

var text = $('.woocommerce-Price-amount.amount').text().substring(1);
console.log(parseFloat(text).toFixed(2));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="woocommerce-Price-amount amount"><span class="woocommerce-Price-currencySymbol">$</span>425.00</span>

注意:这段代码只是为了从文本中返回价格而不是NAN ..但我认为问题不仅仅是这一个,你需要显示.qty以及它在哪里?

更新:如果您的答案中的部分代码有效,并且您需要检查价格来自何处,您可以使用if($el.find('.wholesale_price_container').length)此代码检查如果有任何div已经存在类wholesale_price_container已经存在如果是从它获得全部价格并设置totalQuantity为1因为不需要它

$(document).ready(function(){
  $(".qty").on('change',function() {
    setPriceQ();
  });
})
const setPriceQ = function(){
  $.each(
    $('tr[data-role="product"]'),
    function(index,element){
      const $el = $(element);

      const originalPriceStr = $el.find('.woocommerce-Price-amount.amount').text().replace(/[^\d\.\-]/g, "");
      const originalPrice = parseFloat(originalPriceStr, 10);

      const totalQuantity = $el.find(".qty").val();

      if($el.find('.wholesale_price_container').length){
         originalPriceStr = $el.find('.wholesale_price_container').find('.woocommerce-Price-amount.amount').text().replace(/[^\d\.\-]/g, "");
         originalPrice = parseFloat(originalPriceStr, 10);
         totalQuantity = 1;
      }

      $el.find('#result').html( originalPrice * totalQuantity );     

      }
    );
  };

0
投票

为简单起见,您需要为文本结果解析钱,如下所示:

..text().match(/([0-9]*\.[0-9]{2}|[0-9]+\.[0-9]{2}|[0-9]+)/)[0];

0
投票

谢谢你们,从你们的回答中我得出了自己的代码。这对我来说很完美。

    $(document).ready(function(){
      $(".qty").on('change',function() {
        setPriceQ();
      });
    })

    const setPriceQ = function(){
      $.each(
        $('tr[data-role="product"]'),
        function(index,element){
          const $el = $(element);

          const originalPriceStr = $el.find('.wh-price .woocommerce-Price-amount.amount').text().replace(/[^\d\.\-]/g, "");
          const originalPrice = parseFloat(originalPriceStr, 10);

          const wholesalePriceStr = $el.find('.wh-price .wholesale_price_container .woocommerce-Price-amount.amount').text().replace(/[^\d\.\-]/g, "");
          const wholesalePrice = parseFloat(wholesalePriceStr, 10);   

          const totalQuantity = $el.find(".qty").val();

          if($el.find('.wholesale_price_container').length){
              $el.find('#result').html( '$' + ( wholesalePrice * totalQuantity ) .toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1," ) );
           }
          else {
              $el.find('#result').html( '$' + ( originalPrice * totalQuantity ) .toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1," ) );    
           }
          }
        );
      };    
© www.soinside.com 2019 - 2024. All rights reserved.