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

JavaScript runtime error: Object doesn't support property or method 'contains'

本文关键字:方法 包含 属性 运行时错误 对象 不支持 JavaScript      更新时间:2023-09-26

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

 <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 运行时错误:对象不支持属性或方法'包含'"

除非你自己定义了它(你还没有),否则字符串1 没有 contains() 这样的东西。使用 includes() ,这实际上是一回事。

例:

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()

相关文章: