if语句应为true时返回false

时间:2016-01-18 18:45:41

标签: javascript jquery boolean

我有一个javascript函数来从样式属性中获取属性。

然后检查属性是否等于特定点。

但是,当我console.log()属性的值时,它是预期的,但是当我测试属性值时,它返回false?

这是我的代码和截图:

var $paywhirlWidget = $(".payment-signup-section .container .row .col-xs-12:first-child iframe#paywhirl_frame"),
        $widgetRow = $(".payment-signup-section .container .row .col-xs-12:first-child");

$.fn.inlineStyle = function (prop) {
    var styles = this.attr("style"),
        value;

    styles && styles.split(";").forEach(function (e) {
        var style = e.split(":");
        if ($.trim(style[0]) === prop) {
            value = style[1];
        }
    });
    return value;
};


function checkForChanges() {
    if ($(window).width() < 998) {
        console.log(Boolean($paywhirlWidget.inlineStyle("height").toLowerCase() == "620px"));
        console.log($paywhirlWidget.inlineStyle("height").toLowerCase());
        if ($paywhirlWidget.inlineStyle("height").toLowerCase() == "620px") {
            console.log("im here!!");
            $widgetRow.css("display", "none");
        }
    } else {
        if ($paywhirlWidget.inlineStyle("height") == "300px") {
            console.warn("im here too!!");
            $widgetRow.css("display", "none");
        }
    }
}

setInterval(checkForChanges, 500);

例如,这是&#34; 620px&#34;测试,如您所见,第一个console.log()返回false,即使第二个显示的值正是我正在测试的值!

error

这真令人困惑,因为我无法理解为什么在Boolean测试时,明显为真的值会返回false。

2 个答案:

答案 0 :(得分:1)

看起来你的style属性在值的开头有一个空格。尝试使用trim

$.trim( $paywhirlWidget.inlineStyle("height").toLowerCase() ) === "620px"

或者更新你的inlineStyle插件,以便它进行修剪:

value = $.trim( style[1] );

答案 1 :(得分:1)

更简单地使用jQuery height()返回表示像素的数字

if ($paywhirlWidget.height() == 620) 
相关问题