javascript - 为什么这个 if 总是返回 true?

标签 javascript jquery

<分区>

我正在使用 jquery 检查 div 元素内的字符串,但它总是返回 if never the else 即使 dom 不包含 then $ 我犯了什么愚蠢的错误?

$('.bw-switcher').on('click', function() {
    $(this).toggleClass('toggledrate', 1000);
    $('.toggledrate > .bwswitch-button:before').toggle('fast');
    $('.toggle_rates').toggle('fast');
    if ($(".deatils.dailyPrice:contains($)")) {
        $('.deatils.dailyPrice').toggle('fast');
        console.log('I am the if');
    } else {
        console.log('I am the else');
        $('.deatils.dailyPrice').toggle('fast').prepend('$');
    }
    $('.toggledrate > .bwswitch-button:after').toggle('fast');
});

最佳答案

因为 $(".deatils.dailyPrice:contains($)")是一个对象而不是空对象总是被评估为 trueif测试。

来自 the MDN :

Any value that is not undefined, null, 0, NaN, or the empty string (""), and any object, including a Boolean object whose value is false, evaluates to true when passed to a conditional statement

你可能想要

if ($(".deatils.dailyPrice:contains($)").length) {

关于javascript - 为什么这个 if 总是返回 true?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18217840/

相关文章:

javascript - 嵌套表单密封在 Jquery 中不起作用

javascript - 让DIV加载CSS文件

javascript - Jquery 不使用 bootstrap 4 触发 onchange

javascript - 如何处理 PHP session 超时

Javascript:如何将模板文字与 JSON 一起使用?

javascript - 如何编写一个可以适应稍微不同的用例的 JavaScript 模块?

Jquery 模板不渲染单个项目

javascript - 如何从开发者工具中清除 IE10 & IE11 中的 localStorage?

javascript - 按钮在 "Uncaught SyntaxError: Unexpected token ("中创建 "<DOCTYPE html>"

jquery - 将两个 jQuery .val() 结果合并到变量中