【问题标题】:check if each string is bigger or smaller than a defined value检查每个字符串是否大于或小于定义的值
【发布时间】:2016-10-10 12:51:16
【问题描述】:

我正在尝试使用 jquery 检查给定的字符串是大于还是小于预定义的值。是真还是假 div.property_energy 应该标上某个类。

更新:我的代码没有按预期工作。无论字符串大小,“div.property_energy”始终标记为黄色。

代码如下:

$('.property_energy').each(function () {
        var n = parseInt(this.value);
        if(n < 151){
            $(this).addClass("green");
        }
        else if (n > 300) {
            $(this).addClass("red");
        }
        else{
            $(this).addClass("yellow");
        }
    });

【问题讨论】:

  • 你的问题是?
  • 你看n了吗?我的猜测:它是 NaN,因为 this.value 要么未定义要么不是数字

标签: jquery


【解决方案1】:

在更准确地阅读 jquery 文档后,我自己找到了答案。

    $('.property_energy').each(function () {
    var n = $(this).text();
    if($.isNumeric(n) && n < 151) {
        $(this).addClass("green");
        alert("smaller than 151");
    }
    else if ($.isNumeric(n) && n > 300) {
        $(this).addClass("red");
    }
    else{
        $(this).addClass("yellow");
    }
});

感谢 Johannes H。你的评论让我走上了正确的道路。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-13
    • 2021-03-24
    • 1970-01-01
    • 2014-08-13
    • 2016-06-09
    • 1970-01-01
    • 2017-02-13
    相关资源
    最近更新 更多