jQuery 包含不适用于 Chrome

jQuery contains doesn't work on Chrome

我对 jquery 包含有一个问题。它在 firefox 上运行完美。

这是我的代码。

$("input[data-height='cm']").blur(function(){
    var text = $(this).val();

    if($(this).val().length > 0) {
        if(!$(this).val().contains("cm")) {
            $(this).val(text + " cm");
        }
    }
});

在 chrome 上给出错误

Uncaught TypeError: $(...).val(...).contains is not a function

我该如何解决,请帮忙。

谢谢。

使用indexOf代替contains

 if($(this).val().indexOf("cm") == -1) {
    $(this).val(text + " cm");
 }

你可以使用 test:

if(!/cm/.test($(this).val())) {
    $(this).val(text + " cm");
}

Chrome中没有contains这样的方法。相反,你最好使用 indexOf:

// Instead of...
if ($(this).val().contains('cm')) { /* val() contains 'cm' */ }
// ...do this:
if ($(this).val().indexOf != -1) { /* val() contains 'cm' */ }

请注意 indexOf returns -1 如果未在字符串中找到,>= 0 如果找到。

.contains() 检查 DOM 元素是否是另一个 DOM 元素的后代,因此您应该将它与 jquery 对象一起使用:

这里可以使用indexOf()函数查看value属性的内容

if($(this).val().indexOf("cm")>=0) {

}

您可以参考.contains()了解更多信息。