如何使用ID获取表格数据元素?

时间:2019-07-03 06:48:46

标签: javascript html

我似乎无法抓住元素的内部文本。我已经尝试了许多方法来解决这个问题,但仍然无法完全理解为什么它不起作用。

我已经尝试过通过类,id甚至是元素类型来抓取它。

我希望该函数能够运行,但是却陷入了我在javascript中标记的问题区域。

function updateCartTotal() {
  var cartItemContainer = document.getElementById('cart-table')
  var cartRows = cartItemContainer.rows.length
  var total = 0
  for (var i = 1; i < cartRows; i++) {
    var cartRow = cartRows[i]
    var priceElement = cartRow.getElementById('item-total')[0] //this is the issue ALSO: i have tried removing "[0]"
    var quantityElement = cartRow.getElementsByClassName('form-control')[0] //this is the issue ALSO: i have tried removing "[0]"
    var price = parseFloat(priceElement.innerText.replace('$', ''))
    var quantity = quantityElement.value
    total = total + (price * quantity)
  }
  total = Math.round(total * 100) / 100
  document.getElementsByClassName('cart-total-price')[0].innerText = '$' + total
}
<table class="table table-striped table-border checkout-table" id="cart-table">
  <tbody>
    <tr>
      <td class="hidden-xs">
        <a href="#"><img src="images/intro-04.jpg" alt="[Rainbow Six] Complete Edition" /></a>
      </td>
      <td>
        <h5 class="txt25">[Rainbow Six] Complete Edition</h5>
      </td>
      <td class="txt25" id="item-total">
        $45.00
      </td>
      <td>
        <input class="form-control" type="number" name="" value="1" max="50" min="1" />
      </td>
      <td class="item-total-total txt25">
        $45.00
      </td>
      <td><button class="btn btn-danger" onclick="removeRow(this)" type="button">REMOVE</button></td>
    </tr>
  </tbody>
</table>

1 个答案:

答案 0 :(得分:0)

  • getElementById仅在文档上,不在其他节点上
  • document.getElementById('item-total')将返回一个元素和
  • ID必须是唯一的。
  • 我将<td class="txt25" id="item-total">更改为<td class="txt25 item-total">
  • 我还建议您将class="cart-total-price"更改为id="cart-total-price",因为可能只有一个

尝试使用优于getElementsByClassName的类和querySelector:

function updateCartTotal() {
  [...document.querySelectorAll('cart-table tbody tr')].forEach((cartRow) => {
    var price = cartRow.querySelector('.item-total').innerText.replace(/[$\s]/g,"")
    var quantity = cartRow.querySelector('.form-control').value;
    total += (+price * +quantity)
  });
  document.querySelector('.cart-total-price').innerText = '$' + total.toFixed(2)
}

对于旧版浏览器支持,您可以将第一行更改为

var cartRows = document.querySelectorAll('cart-table tbody tr')
for (var i=0, cartRow;i<cartRows.length; i++) {
  cartRow = cartRows[i];