【问题标题】:Jquery cannot skipped evaluation of first json resultJquery 不能跳过对第一个 json 结果的评估
【发布时间】:2015-04-17 00:25:22
【问题描述】:

我想评估一组 JSON 结果,但不知何故总是跳过第一个结果。我的 Jquery 代码如下:

function check_product_cash_discount(total_id){
        //check for cash discount
        $.ajax({
            url:siteurl+"checkout/get_cash_discount_ajax/",
            type:"POST",
            success:function(res){
                var parsed = JSON.parse(res);
                var this_product_total = $(total_id).text();
                $.each(parsed,function(k,v){                            
                    var amount = v.cash_discount_amount;
                    //console.log(v);
                    if(this_product_total >= amount){
                        $(total_id).text(v.cash_discount_percentage);   
                        console.log(amount);
                    }
                });                             
            }
        });
    }

AJAX 调用的结果是“res”,我用 JSON.parse 对其进行了解析,并将其放入“parsed”中。 console.log(v) 和 $.each 时结果的 value(v) 如下:

Object {cash_discount_id: "4", cash_discount_amount: "1000", cash_discount_percentage: "10"}
Object {cash_discount_id: "3", cash_discount_amount: "800", cash_discount_percentage: "8"}
Object {cash_discount_id: "2", cash_discount_amount: "300", cash_discount_percentage: "7"}

我的问题是:当变量“this_product_total”小于“if”语句中的变量“amount”时,为什么它会跳过第一个 JSON 结果对象?当我 console.log(amount) 时,当变量“this_product_total”中的文本为 512.89 时,日志显示 1000、300 和 200?当我使用 $.isNumeric(); 评估它们时,“数量”和“thid_product_total”中的值是正确的;请帮忙。

【问题讨论】:

  • 512 显然不是>= 到 1000。此外,如果多个项目确实满足条件,您每次都会重写文本
  • @charlietfl 那么如何让它匹配只说 300?

标签: javascript jquery ajax json


【解决方案1】:

这样做的问题是金额“1000”被视为字符串。所以我不得不 parseInt(amount) 并且解决了 1000 的问题,我添加了一个中断;到 if(this_product_total >= amount) 以便一旦找到第一个匹配条件,它就会停止循环......

【讨论】:

  • 别忘了加上radix参数! parseInt(amount, 10)
  • 另外,break 不会在 $.each 函数中执行任何操作,因为它不是真正的循环。您必须在 $.each 回调中使用 return false 才能停止迭代。
猜你喜欢
  • 2011-01-07
  • 1970-01-01
  • 2018-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-16
  • 2011-07-17
  • 1970-01-01
相关资源
最近更新 更多