JavaScript 文件中的代码如何获取文件的 URL? [英] How can code in a JavaScript file get the file's URL?
问题描述
我需要将 CSS 样式表动态加载到位于不同域的页面中.如何获取要在样式表的 href 属性中使用的 JS 文件的完整 URL?
I need to dynamically load a CSS stylesheet into a page that's on a different domain. How can I get the complete URL of the JS file to use in the href attribute of the stylesheet?
例如,这是结构:
http://bla.com/js/script.js
http://bla.com/css/style.css
我想将样式表动态加载到页面中 http://boo.net/index.html.问题是,我事先不知道 bla.com 位,只是样式表在 ../css/ 中相对于 JS 文件这一事实.
I want to dynamically load the stylesheet into a page http://boo.net/index.html. The problem is, I don't know the bla.com bit in advance, just the fact that the stylesheet is in ../css/ relative to the JS file.
当然,脚本包含在 index.html 中.jQuery 也不错.
The script is, of course, included on index.html. jQuery's fine too.
推荐答案
为脚本标签添加 ID:
Add an ID to the script tag:
<script type="text/javascript" id="myScript" src="http://bla.com/js/script.js"></script>
在 http://bla.com/js/script.js
中:
var myScript = document.getElementById('myscript');
var myScriptSrc = myScript.getAttribute('src');
alert(myScriptSrc); // included for debugging
您应该能够操作 myScriptSrc
的值来获取 bla.com
上任何其他内容的路径.
You should be able to manipulate the value of myScriptSrc
to obtain the path to any other content on bla.com
.
我认为这个示例是什么 James Black 在他的回答中是指.
I think this sample is what James Black meant in his answer.
最后,给大家建议使用document.location
,请记住,如果你想只读访问当前页面地址,你应该使用document.URL
或 window.location
.如果你想设置页面地址,你应该总是使用window.location.href
.尽管 window.location = 'location';
有效,但看到一个字符串被分配给一个位置总是让我感到困扰.我不知道为什么,因为 JavaScript 允许各种其他隐式类型转换.
Lastly, to everyone suggesting the use of document.location
, please keep in mind that if you want read-only access to the current page address, you should be using document.URL
or window.location
. If you want to set the page address, you should always use window.location.href
. Although window.location = 'location';
works, it has always bothered me to see a String being assigned to a Location. I'm not sure why since JavaScript allows all sorts of other implicit type conversions.
- mozilla 参考:
document.location
最初是一个只读属性,尽管 Gecko 浏览器也允许您分配给它.为了跨浏览器安全,请改用 window.location.要仅检索 URL 作为字符串,只读 document.URL可以使用属性. - Sun 参考:不要使用 location 作为
document
对象的属性;请改用 document.URL 属性.document.location
属性是document.URL
的同义词,已弃用.
- mozilla reference:
document.location
was originally a read-only property, although Gecko browsers allow you to assign to it as well. For cross-browser safety, use window.location instead. To retrieve just the URL as a string, the read-only document.URL property can be used. - Sun reference: Do not use location as a property of the
document
object; use the document.URL property instead. Thedocument.location
property, which is a synonym fordocument.URL
, is deprecated.
这篇关于JavaScript 文件中的代码如何获取文件的 URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!