window.location.indexOf无法在Javascript中工作 [英] window.location.indexOf not working in Javascript
问题描述
以下是我所拥有的。
var myString = "http://localhost:8888/www.smart-kw.com/";
alert(myString.indexOf("localhost"));
这给我提醒......但是如果我改变 var myString = http:// localhost:8888 / www.smart-kw.com /;
到 var myString = window.location;
,它赢了工作(我没有得到提醒)。
This give me alert... however if I change var myString = "http://localhost:8888/www.smart-kw.com/";
to var myString = window.location;
, it won't work (I don't get alert).
var myString = window.location;
alert(myString.indexOf("localhost"));
推荐答案
window.location
是一个访问者属性,并获取它的值为您提供了一个对象,而不是字符串,因此它没有 indexOf
函数。 (人们有时认为它是一个字符串是完全可以理解的,因为当你设置它的值时,访问者属性的setter接受一个字符串;也就是说, window.location =some url ;
实际上有效。但是当你获取它时,你没有得到一个字符串。)
window.location
is an accessor property, and getting its value gives you an object, not a string, and so it doesn't have an indexOf
function. (It's perfectly understandable that people sometimes think it's a string, since when you set its value, the accessor property's setter accepts a string; that is, window.location = "some url";
actually works. But when you get it, you don't get a string.)
你可以使用 window.location.toString()
, String(window.location)
或 window.location.href
如果你愿意,可以获取一个字符串,或者使用它的各种属性来检查细节。从链接中,给出示例url http://www.example.com:80/search?q=devmo#test
:
You can use window.location.toString()
, String(window.location)
, or window.location.href
to get a string for it if you like, or use any of its various properties to check specifics. From the link, given example url http://www.example.com:80/search?q=devmo#test
:
-
hash
:#符号后面的URL部分,包括#符号。您可以侦听hashchange事件以获得有关支持浏览器的哈希更改的通知。
示例:#test
-
host
:主机名和端口号。
示例:www.example.com:80
-
主机名
:主机名(没有端口号)。
示例:www.example.com
-
href
:整个网址。
示例:http://www.example.com:80/search?q=devmo#test
-
路径名
:路径(相对于主机)。
示例:/ search
-
port
:网址的端口号。
示例:80
-
protocol
:协议URL。例如:http:
-
search
:URL后面的部分是?符号,包括?例如:?q = devmo
hash
: The part of the URL that follows the # symbol, including the # symbol. You can listen for the hashchange event to get notified of changes to the hash in supporting browsers.
Example:#test
host
: The host name and port number.
Example:www.example.com:80
hostname
: The host name (without the port number).
Example:www.example.com
href
: The entire URL.
Example:http://www.example.com:80/search?q=devmo#test
pathname
: The path (relative to the host).
Example:/search
port
: The port number of the URL.
Example:80
protocol
: The protocol of the URL.
Example:http:
search
: The part of the URL that follows the ? symbol, including the ? symbol.
Example:?q=devmo
例如,对于您的引用示例,您可以检查 window.location.hostname ===localhost
。
For instance, for your quoted example, you might check window.location.hostname === "localhost"
.
这篇关于window.location.indexOf无法在Javascript中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!