窗口之间有什么区别。Location和document。Location ?它们是否都引用同一个对象?
当前回答
我更喜欢使用文档。位置,尽管位置,文档。位置和窗口。Location返回相同的对象。
使用文件的原因。地点是:
窗口的浏览器兼容性部分。位置提到
在Firefox 57之前,通过URL api访问URL时,URL中包含的单引号会被转义。参见bug 1386683。
文档的浏览器兼容性部分。位置提到
全力支持。
Mdn location reference uses document.location in their examples. // location: https://developer.mozilla.org:8080/en-US/search?q=URL#search-results-close-container const loc = document.location; console.log(loc.href); // https://developer.mozilla.org:8080/en-US/search?q=URL#search-results-close-container console.log(loc.protocol); // https: console.log(loc.host); // developer.mozilla.org:8080 console.log(loc.hostname); // developer.mozilla.org console.log(loc.port); // 8080 console.log(loc.pathname); // /en-US/search console.log(loc.search); // ?q=URL console.log(loc.hash); // #search-results-close-container console.log(loc.origin); // https://developer.mozilla.org:8080 location.assign('http://another.site') // load another page
其他回答
窗口。考虑到较老的浏览器,位置是两者中更可靠的一致性。
至少在IE中,它在本地文件上有一点不同:
文档。URL将返回 ”文件:/ / C: \ \ abc \ a.html项目”
但是window。location。href会返回 “文件:/ / / C: / / abc / a.html”项目
一个是反斜杠,一个是正斜杠。
我更喜欢使用文档。位置,尽管位置,文档。位置和窗口。Location返回相同的对象。
使用文件的原因。地点是:
窗口的浏览器兼容性部分。位置提到
在Firefox 57之前,通过URL api访问URL时,URL中包含的单引号会被转义。参见bug 1386683。
文档的浏览器兼容性部分。位置提到
全力支持。
Mdn location reference uses document.location in their examples. // location: https://developer.mozilla.org:8080/en-US/search?q=URL#search-results-close-container const loc = document.location; console.log(loc.href); // https://developer.mozilla.org:8080/en-US/search?q=URL#search-results-close-container console.log(loc.protocol); // https: console.log(loc.host); // developer.mozilla.org:8080 console.log(loc.hostname); // developer.mozilla.org console.log(loc.port); // 8080 console.log(loc.pathname); // /en-US/search console.log(loc.search); // ?q=URL console.log(loc.hash); // #search-results-close-container console.log(loc.origin); // https://developer.mozilla.org:8080 location.assign('http://another.site') // load another page
窗口。位置在所有兼容的浏览器上都是读/写的。
文档。location在Internet Explorer(至少)中是只读的,但在基于gecko的浏览器(Firefox, SeaMonkey)中是读/写的。
有趣的是,如果你有一个名为'location'的框架、图像或窗体,那么'document. properties '则为'location . properties '。location'提供了对框架窗口、图像或窗体的引用,而不是location对象。显然,这是因为文件。表单、文档。image和window.frames集合名称查找优先于window.location的映射。
<img name='location' src='location.png'>
if (document.location.tagName == 'IMG') alert('Hello!')