jQuery 使用类在当前表行中查找输入字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2169472/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Find input fields in current table row with class
提问by Fred Bergman
I am making a book shop and want to add a fancy jQuery order form. The point is that the user shall choose the quantity of a book with a minus and plus button and then let JavaScript calculate a total sum for that book.
我正在做一家书店,想添加一个漂亮的 jQuery 订单。关键是用户应该用减号和加号按钮选择一本书的数量,然后让 JavaScript 计算这本书的总和。
I have a markup as follows:
我有一个标记如下:
<tr>
<td><p>Book title</p></td>
<td><p><a href="#" class="bookDecrement">-</a><input type="text" class="bookQuantity disabled" disabled /><a href="#" class="bookIncrement">+</a></p></td>
<td><p><input type="text" class="bookPrice disabled" value="70" disabled /></p></td>
<td><p>=</p></td>
<td><p><input type="text" class="bookTotal disabled" disabled /></p></td>
</tr>
How do I reach the bookPrice and bookTotal class in this row with jQuery? Since I have multiple book titles I need to only access the input filed in the current row.
如何使用 jQuery 到达此行中的 bookPrice 和 bookTotal 类?因为我有多个书名,所以我只需要访问当前行中的输入。
Thanks!
谢谢!
回答by Tatu Ulmanen
This should do it:
这应该这样做:
$('.bookDecrement, .bookIncrement').click(function() {
// Get the current row
var row = $(this).closest('tr');
// Determine if we're adding or removing
var increment = $(this).hasClass('bookDecrement') ? -1 : 1;
// Get the current quantity
var quantity = parseInt(row.find('.bookQuantity').val(), 10);
// Adjust the quantity
quantity += increment;
// Quantity must be at least 0
quantity = quantity < 0 ? 0 : quantity;
// Get the price
var price = parseFloat(row.find('.bookPrice').val());
// Adjust the total
row.find('.bookTotal').val(quantity * price);
// Return false to prevent the link from redirecting to '#'
return false;
});
回答by Chetan Sastry
You can get to the ancestor tr and descend again to the input within. Like this:
您可以到达祖先 tr 并再次下降到其中的输入。像这样:
$("a.bookIncrement").click(function() {
$(this).closest("tr").find("input.bookPrice").doSomething();
});