通过 jquery 获得价值

Getting value with jquery

我有这样的脚本

$(document).ready(function () {
        var sum = 0;
        $('.price_jq').each(function () {
            var price = $(this);
            alert(price.html());
            var count = price.parent().find('.count_jq');
            alert(count.html());
            sum = (price.html() * count.val());
            $('.cart_total_price').append(sum + "₴");
        });
    });

我的html

<table>
  <td class="cart_price">
     <p class="price_jq">{{ product.price }}</p>
  </td>
     <input size="2" name="count" value="2" class="count_jq" type="text"/>
  <td class="cart_total">
     <p class="cart_total_price"></p>
  </td>
</table>

当我提醒价格时,我得到了我的价值,但是当我想要计数时,我得到了 NaN。我做错了什么?

您的 HTML 代码不正确,因此您要查找的输入很可能完全在 table 之外。这取决于每个浏览器如何处理不正确的 HTML 代码。

您需要 table 行来放入 table 个单元格,并且 table 中的所有内容都必须在 table 个单元格中。例如:

<table>
  <tr>
    <td class="cart_price">
      <p class="price_jq">{{ product.price }}</p>
    </td>
    <td>
      <input size="2" name="count" value="2" class="count_jq" type="text"/>
    </td>
  </tr>
  <tr>
    <td class="cart_total">
      <p class="cart_total_price"></p>
    </td>
  </tr>
</table>

对于上面的代码,您将使用 .parent().parent().find('.count_jq').closest('tr').find('.count_jq') 从价格元素中查找计数元素:

$(document).ready(function () {
    var sum = 0;
    $('.price_jq').each(function () {
        var price = $(this);
        var count = price.closest('tr').find('.count_jq');
        sum = (price.html() * count.val());
        $('.cart_total_price').append(sum + "₴");
    });
});

我不知道您的要求,但我认为您可能希望将值添加到总和并将其放入循环后的元素中,而不是为循环中的每个项目添加值:

$(document).ready(function () {
    var sum = 0;
    $('.price_jq').each(function () {
        var price = $(this);
        var count = price.closest('tr').find('.count_jq');
        sum += (price.html() * count.val());
    });
    $('.cart_total_price').append(sum + "₴");
});