gpt4 book ai didi

javascript - 如何获取前一个元素中的文本并进行一些数学运算

转载 作者:行者123 更新时间:2023-11-30 10:48:19 25 4
gpt4 key购买 nike

我有以下结构:

<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);
});
});
});

但是 price 返回 nil(即使 price 通过我的 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);
});

最佳答案

要获取上一个/下一个元素,您可以使用以下内容:

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);
});
});

Working Demo

关于javascript - 如何获取前一个元素中的文本并进行一些数学运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7027324/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com