Javascript从表中提取数据

标签 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;
}

有什么想法吗?

最佳答案

我会直接选择小计数据属性:

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

<强> DEMO

关于Javascript从表中提取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46544210/

相关文章:

javascript - 如何在没有 jQuery 的情况下进行 AJAX 调用?

c# - Selenium 网络驱动程序 : how to deal with javascript onclick in C#

javascript - 将 img src 替换为 data-img

具有 2 个 Controller 的 Angular 服务中的 Javascript Getter/Setter

javascript - 使用 morgan 创建记录器中间件

javascript - 无需在 call() 调用的函数内写入 'this' 吗?

javascript - 通过Yii2表单插入数据时获取空值

javascript - 为什么 Object.prototype.toString.call(arr) 返回 [object Object] 而不是 [object Array]?

javascript - 如何显示/绘制以数字为输入的屏幕锁定图案

javascript - 类似 HTML 应用程序的页面