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
函数.(人们有时认为它是一个字符串是完全可以理解的,因为当您设置它的值时,访问器属性的设置器接受一个字符串;即,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
来获取如果您愿意,可以使用一个字符串,或者使用 其各种属性中的任何一个 检查细节.从链接中,给出示例网址 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
hostname
:主机名(不含端口号).
示例:www.example.com
href
:整个 URL.
示例:http://www.example.com:80/search?q=devmo#test
pathname
:路径(相对于主机).
示例:/search
port
:URL 的端口号.
示例:80
protocol
:URL 的协议.
示例:http:
search
:URL 中 ?符号,包括?符号.
示例:?q=devmo
例如,对于您引用的示例,您可以检查 window.location.hostname === "localhost"
.
For instance, for your quoted example, you might check window.location.hostname === "localhost"
.
这篇关于window.location.indexOf 在 Javascript 中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!