我试图返回quantity类的值,但一直得到NaN。我可以访问价格类,但不能访问数量。不同之处在于数量有一个输入。
<body>
<tr>
<td class="item pr-5">Sample</td>
<td class="price pr-5">25.33</td>
<td class="quantity pr-5"><input type="number" value="1" /></td>
<td class="subtotal pr-5">$25.33</td>
<td>
<button class="btn btn-danger btn-sm remove">
Remove Item
</button>
</td>
</tr>
</tbody>$(document).ready(function () {
$('tbody tr').each(function (i, ele) {
var price = parseFloat($(ele).children('.price').text());
console.log(price);
var quantity = parseFloat($(ele).children('.quantity').text());
console.log(quantity); // NaN
var subtotal = price * quantity;
// console.log(subtotal);
});
});发布于 2020-05-12 23:20:11
在reach input标记中使用find()方法而不是使用两个children方法。并从input标记中获取值,使用val()而不是text()。
var quantity = parseFloat($(ele).find('.quantity input').val());
$(document).ready(function() {
$('tbody tr').each(function(i, ele) {
var price = parseFloat($(ele).children('.price').text());
console.log(price);
var quantity = parseFloat($(ele).find('.quantity input').val());
console.log(quantity); // NaN
var subtotal = price * quantity;
// console.log(subtotal);
});
});<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td class="item pr-5">Sample</td>
<td class="price pr-5">25.33</td>
<td class="quantity pr-5"><input type="number" value="1" /></td>
<td class="subtotal pr-5">$25.33</td>
<td>
<button class="btn btn-danger btn-sm remove">
Remove Item
</button>
</td>
</tbody>
</table>
发布于 2020-05-12 23:16:47
这是因为<td class="quantity pr-5"><input type="number" value="1" /></td>这一行。此行没有text,但它有另一个子项
$(document).ready(function() {
$('tbody tr').each(function(i, ele) {
var price = parseFloat($(ele).children('.price').text());
console.log(price);
var quantity = parseFloat($(ele).children('.quantity').text());
console.log(quantity); // NaN
var subtotal = price * quantity;
// console.log(subtotal);
});
});<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<table>
<tr>
<td class="item pr-5">Sample</td>
<td class="price pr-5">25.33</td>
<td class="quantity pr-5"><input type="number" value="1" /></td>
<td class="subtotal pr-5">$25.33</td>
<td>
<button class="btn btn-danger btn-sm remove">
Remove Item
</button>
</td>
</table>
发布于 2020-05-12 23:26:52
谢谢,我能够解决这个问题:
var quantity = parseFloat($(ele).children('.quantity').children().val());https://stackoverflow.com/questions/61755307
复制相似问题