gpt4 book ai didi

javascript - 根据输入值更改 div 内容

转载 作者:行者123 更新时间:2023-12-03 11:47:45 25 4
gpt4 key购买 nike

我有一个包含一些数据的 json 文件。我尝试做的是获取输入值,然后当它与折扣规则之一匹配时,价格字段应更改为适当的价格。

我的 JSON:

{
"product": {

"discounts": {

"10": {
"id": "151203",
"quantity": "10",
"price": {
"price": 5.35

},
"percentage": 0.05,
"unit": false
},

"50": {
"id": "151204",
"quantity": "50",
"price": {
"price": 4.95

},
"percentage": 0.12,
"unit": false
}

}

}
} //etc

我的 HTML

<div class="quantity" id="wqs-quantity">
<input type="text" name="quantity" value="1">
</div>

到目前为止我的jquery:

var qty = $('#wqs-quantity input').val();
$('#wqs-quantity input').change(function(e){
if(qty == discount.quantity){
$('.wqs-price .item-price').text(discountPrice);
}
});

这段代码位于 getJSON 调用内。

现在价格字段始终更改为 4.95。所以我尝试的是,当有人填写 10 或 50 时,价格字段会更改为 €5.35 或 €4.95...

有人知道我做错了什么吗?

最佳答案

1) 您错过了“折扣”的空缺:{ [第 3 行]

2) if 语句是否在循环中遍历所有可能的“折扣”?

尝试使用像这样的循环(其中值 p 是 JSON 对象):

    $('#wqs-quantity input').change(function(e){
var qty = $(this).val();
var d = p.product.discounts;

for (var key in d) {
if (d.hasOwnProperty(key)) {
if (qty == d.key.quantity) {
$('.wqs-price .item-price').text(discountPrice);
}
}
}

});
3) 如果数量至少达到折扣中的数量时必须应用折扣(因此数量 10 起 5% 折扣,50 件以上 12% 折扣)。然后您可以使用此循环(它检查每个数量阈值并保存最后一个适用的阈值):
    var p = JSON.parse(data);

$('#wqs-quantity input').change(function(e){
// get new quantity
var qty = $(this).val();

// get discount thresholds
var d = p.product.discounts;

// the current value to fall back on
var new_price = $('.wqs-price .item-price').text();

// loop through all discounts
for (var key in d) {
if (d.hasOwnProperty(key)) {
var diff = (qty-d[key].quantity);

// check if current quantity is above (or the same as) the threshold
if (diff >= 0) {
new_price = d[key].price.price;
}
}
}

$('.wqs-price .item-price').text(new_price);

});
(为此,不同的“折扣”应按照数量阈值从最低到最高的顺序排列。)

4) 为什么在“price”中使用对象“price”? (例如“discounts.10.price.price”而不是“discounts.10.price”)

工作示例:http://jsfiddle.net/PhilQ/ga59vbx3/11

关于javascript - 根据输入值更改 div 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25980128/

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