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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19510110/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 15:50:22  来源:igfitidea点击:

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

javascript

提问by Billy

I have written the below code in Master Page

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

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

In asp.net application, I have three pages page1, page2,page3 which are inherited by the same Master Page. When I am trying to access the page3, it is displaying error: "JavaScript runtime error: Object doesn't support property or method 'contains'"

在asp.net 应用程序中,我有三个页面page1、page2、page3,它们由同一个母版页继承。当我尝试访问 page3 时,它显示错误:“JavaScript 运行时错误:对象不支持属性或方法‘包含’”

回答by Qantas 94 Heavy

Unless you have defined it yourself (which you haven't), there's no such thing as contains()for strings1. Use includes(), which is practically the same thing.

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

Example:

例子:

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

If you have to support older browsers (like Internet Explorer), use indexOf():

如果您必须支持旧浏览器(如 Internet Explorer),请使用indexOf()

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

Anyway, it is a horrible idea to use two different versions of jQuery on two pages - avoid it where possible.

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



1:Technically this isn't 100% true: at one point there was a built-in contains()function, but it was renamed to includes()for compatibility reasons.

1:从技术上讲,这不是 100% 正确:曾经有一个内置contains()函数,但includes()出于兼容性原因将其重命名