我有以下结构:
<table>
<tr>
<td>first</td>
<td class="price">__</td>
<td><input type="text" class="quantity"></td>
<td class="amount></td>
</tr>
</table>
在<td class="price">
内部传递一个通过AJAX函数检索的值。
所以我在我的javascript文件中有这个:
jQuery(function($) {
$(document).ready(function() {
// alert('document ready');
$("input.quantity").live("blur", function() {
var $this = $(this);
quantity = $this.val();
price = $this.prev("td.price").text();
alert(price);
amount = quantity * price;
$this.next("td.amount").html(amount);
});
});
});
但价格回报为零(甚至价格在我的ajax函数中正确加载)
编辑:这是遵循以下所有建议的最终代码。谢谢大家!
$("input.quantity").live("blur", function() {
var $this = $(this);
quantity = parseInt($this.val()); // in this case, people can't buy a 1 item and a half for example.
price = $this.parents("tr").find("td.price").text();
price = parseFloat(price); // price can have "cents"
amount = quantity * price;
amount = Number(amount).toFixed(2); // I should be able to see at least 2 first decimal digits from the amount.
$this.parent().next("td.amount").html(amount);
});
答案 0 :(得分:1)
尝试:
jQuery(function($) {
$(document).ready(function() {
// alert('document ready');
$("input.quantity").live("blur", function() {
var $this = $(this);
quantity = $this.val();
price = $this.parent().siblings("td.price").text();
price=parseFloat(price);
alert(price);
amount = quantity * price;
$this.parent().siblings("td.amount").html(amount);
});
});
});
答案 1 :(得分:1)
答案 2 :(得分:1)
答案 3 :(得分:1)
要获取上一个/下一个元素,您可以使用以下内容:
parseInt($this.parent().prev("td.price").text()); //or parseFloat
和强>
parseInt($this.parent().next("td.amount").text()); //or parseFloat
完整代码:
jQuery(function($) {
$(document).ready(function() {
$("input.quantity").live("blur", function() {
var $this = $(this);
quantity = parseInt($this.val());
alert("Quantity : " + quantity);
price = parseInt($this.parent().prev("td.price").text());
alert("Price : " + price);
amount = quantity * price;
$this.parent().next("td.amount").html(amount);
alert("Amount : " + amount);
});
});