gpt4 book ai didi

javascript - 为什么输入 val() 没有实时变化?

转载 作者:行者123 更新时间:2023-11-28 19:55:18 25 4
gpt4 key购买 nike

我有一个基本的form用户选择 option并输入数量。进入input然后一个基本的 jquery 脚本将这些数字相乘得到总数。但唯一的问题是它不能实时更新。你必须亲自看看:http://jsfiddle.net/iamjosan/4T9Wq/

$('.setPrice').on('change', function () {

var s = +$(this).find('option:selected').data('price');
var q = +$('#quantity').val();

if (q > 1) {
var price = s * q;
} else {
price = s;
}

$('#showPrice').val(price.toFixed(2));
});

如何让脚本实时更新值?

编辑

更改 input选择 option 后的值(大于 1)结果为 NaN,但更改 input选择 option 之前的值显示真实值(value)。

最佳答案

使用inputkeyup ,自 change不会实时触发,具体取决于浏览器:

The input event fires whenever the user has modified the data of the control. The change event fires when the value is committed, if that makes sense for the control, or else when the control loses focus. In all cases, the input event comes before the corresponding change event (if any). (source)

此外,在您的具体情况下,您需要从正确的元素检查商品的价格:

var s = +$("#size").find('option:selected').data('price');

不要忘记添加 id属性正确<select> 。否则,您将在当前元素上下文中查找选定的选项,这可能是 <input> .

总体(fiddle):

$('.setPrice').on('keyup change', function () {     
var s = +$("#size").find('option:selected').data('price');
var q = +$('#quantity').val();
var price = q > 1 ? s * q : s;
$('#showPrice').val(price.toFixed(2));
});

请注意,我添加了 change ,因为您通常不使用键盘 <select> (但您可以这样做,这就是为什么将 keyup 添加到该元素可能是个好主意)。

关于javascript - 为什么输入 val() 没有实时变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22699144/

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