JavaScript运行时错误:对象不支持属性或方法“contains”。

5

我已经在母版页中编写了以下代码

 <script type="text/javascript">
            if (window.location.pathname.contains('Page1.aspx')) {
                var js = document.createElement("script");

                js.type = "text/javascript";
                js.src = 'http://code.jquery.com/jquery-1.8.3.js';


            }
            if (window.location.pathname.contains('Page2.aspx')) {
                var js = document.createElement("script");

                js.type = "text/javascript";
                js.src = 'http://code.jquery.com/jquery-1.9.1.js';


            }    

        </script>

在asp.net应用程序中,我有三个页面page1、page2、page3,它们都继承了相同的主页。当我尝试访问page3时,它显示错误:"JavaScript运行时错误:对象不支持属性或方法'contains'"。

你为什么在两个页面上使用不同版本的jQuery? - Qantas 94 Heavy
由于主页面中的jQuery冲突。 - Billy
1个回答

10

除非你自己定义了它(而你没有),否则字符串中不存在contains()函数1。使用includes()函数,它几乎与contains()相同。

例如:

console.log('abcdefg'.includes('def')); // true
console.log('abcdefg'.includes('ghi')); // false

如果您需要支持旧版浏览器(如Internet Explorer),请使用indexOf()

console.log('abcdefg'.indexOf('def') !== -1); // true
console.log('abcdefg'.indexOf('ghi') !== -1); // false

无论如何,在两个页面上使用两个不同版本的jQuery是一个可怕的想法 - 尽可能避免。


1: 从技术上讲,这并不是100%正确的:曾经有一个内置的contains()函数,但由于兼容性原因被重命名为includes()(参考链接)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接