jQuery使用类更改表中的数值

时间:2019-05-03 14:31:39

标签: jquery

我试图通过将类<td>乘以2来更改所有.price中的值。 使用下面的jquery代码,我将使用类text调用所有值(price s),但是我很难找到一种方法来将其相乘并显示在同一<td>中。 32000应该是64000,而12000应该是24000。 帮助将不胜感激。

JQUERY:

$(".price").each(function() {

                var value = $(this).text();

                if(!isNaN(value) && value.length != 0) {
                    sum += parseFloat(value);
                }

HTML:

<table>
       <thead>
        <tr>
         <th><span>Item</span></th>
         <th><span>Price</span></th>
        </tr>
       </thead>
    <tbody>
    <tr>
       <td class="name">a</td>
       <td class="price">32000</td>
    </tr>

    <tr>
       <td class="name">b</td>
       <td class="price">12000</td>
    </tr>
</tbody>
</table>

2 个答案:

答案 0 :(得分:1)

您可以使用.each()遍历price类元素,然后使用$(this).text()获取(并设置)相应元素的文本。然后,用* 2乘以2只是一个简单的问题。像这样:

$(".price").each(function() {
  $(this).text($(this).text() * 2)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
HTML:

<table>
  <thead>
    <tr>
      <th><span>Item</span></th>
      <th><span>Price</span></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td class="name">a</td>
      <td class="price">32000</td>
    </tr>

    <tr>
      <td class="name">b</td>
      <td class="price">12000</td>
    </tr>
  </tbody>
</table>

答案 1 :(得分:0)

您可以像这样对多个2使用位移位

$(".price").each(function() {
  $(this).text(parseInt($(this).text()) << 1)
})

$(".price").each(function() {
  $(this).text(parseInt($(this).text()) << 1)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
HTML:

<table>
  <thead>
    <tr>
      <th><span>Item</span></th>
      <th><span>Price</span></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td class="name">a</td>
      <td class="price">32000</td>
    </tr>

    <tr>
      <td class="name">b</td>
      <td class="price">12000</td>
    </tr>
  </tbody>
</table>