Javascript从表中提取数据

时间:2017-10-03 12:05:01

标签: javascript

我有下表:

  <table id="cart-subtotals" cellspacing="0" class="shop_table 
  shop_table_responsive">
  <tbody>
  <tr class="cart-subtotal">
  <th>Subtotal</th>
  <td data-title="Subtotal"><span class="woocommerce-Price-amount amount">
  <span class="woocommerce-Price-currencySymbol">£</span>165</span></td>
  </tr>
  <tr class="shipping">
  <th>Shipping</th>
  <td data-title="Shipping"> Standard Delivery: <span class="woocommerce-
   Price-amount amount"><span class="woocommerce-Price-
   currencySymbol">£</span>9</span> <input type="hidden" 
   name="shipping_method[0]" data-index="0" id="shipping_method_0" 
  value="flat_rate:2" class="shipping_method"></td>
  </tr>
  <tr class="order-total">
  <th>Total</th>
  <td data-title="Total"><strong><span class="woocommerce-Price-amount 
  amount"><span class="woocommerce-Price-currencySymbol">£</span>174</span>
  </strong> <small class="includes_tax">(includes <span class="woocommerce-
  Price-amount amount"><span class="woocommerce-Price-
  currencySymbol">£</span>7.86</span> Reduced Rate, <span 
  class="woocommerce-Price-amount amount"><span class="woocommerce-Price-
  currencySymbol">£</span>1.50</span> VAT)</small></td>
  </tr>
  </tbody>
  </table>

我需要从表格中的第一个中提取'165'的值(并排除货币符号)。

我尝试了以下但是不起作用:

function() {
  var element = document.querySelector('#cart-subtotal td:first');
  var price = element.innerHTML.match(/\d*\.\d*/)[0]; 

  return price;
}

有什么想法吗?

4 个答案:

答案 0 :(得分:2)

我会直接找到小计数据属性:

const subtotal = document.querySelector('td[data-title="Subtotal"]');
const price - subtotal.textContent.match(/\d+/)[0]; // 165

<强> DEMO

答案 1 :(得分:2)

问题在于您尝试获取元素

(function() {
    var element = document.querySelector('.cart-subtotal td:nth-child(2)');
    var price = element.innerHTML.match(/\d+/)[0];
    console.log(price)
    return price;

    })()

试试这个有效

答案 2 :(得分:0)

试试这个:

var value = document.getElementsByClassName("woocommerce-Price-amount amount")[0].innerHTML;
value = value.split("</span>");
value = value[1];
console.log(value); //165

答案 3 :(得分:-1)

试试这个代码段:

function ExtractSpanValue() {
       var TRValue = document.querySelector(".cart-subtotal");
        if (TRValue != null) {
            var SpanValue = TRValue.querySelector(".woocommerce-Price-amount");
            if (SpanValue != null && SpanValue.childNodes != null && SpanValue.childNodes.length>2)
    return SpanValue.childNodes['2'].textContent.trim();
    }
}