Javascript javascript获取当前文件脚本路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8523200/
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
javascript get current filescript path
提问by pleerock
How can I get the path of the current script in javascript using jQuery
如何使用jQuery在javascript中获取当前脚本的路径
for example I have site.com/js/script.js
and there is a code in this script:
例如我有site.com/js/script.js
并且在这个脚本中有一个代码:
$(document).ready(function() {
alert( ... this code ... );
}
It Should return alert box with the "/js/script.js" message. This function should work like magic __FILE__
constant in php
它应该返回带有“/js/script.js”消息的警告框。这个函数应该像__FILE__
php 中的魔法常量一样工作
So, why do I need this?
那么,我为什么需要这个?
I want to set background image dynamically:
我想动态设置背景图像:
$("somediv").css("background-image", "url(" + $SCRIPT_PATH + "/images/img.png)");
and images directory is the /js
directory, near the script.js
file
和图像目录是/js
目录,靠近script.js
文件
and js
folder's name can be dynamically set, so script and images can be in the /myprogect/javascript-files
directory
并且js
文件夹的名称可以动态设置,因此脚本和图像可以在/myprogect/javascript-files
目录中
回答by meouw
You can rely on the fact that each <script>
element has to be evaluated* before the next one is inserted into the DOM.
您可以依赖这样一个事实,即<script>
在将下一个元素插入到 DOM 之前,必须对每个元素进行评估*。
This means that the script currently evaluated (as long as it is part of your markup and not dynamically inserted) will be the last one in the NodeList
retrieved with getElementsByTagName( 'script' )
.
这意味着当前评估的脚本(只要它是标记的一部分并且不是动态插入的)将是NodeList
使用getElementsByTagName( 'script' )
.
This allows you to read that elements src attribute and from that determine the folder that the script is being served from - like this:
这允许您读取该元素的 src 属性,并从中确定提供脚本的文件夹 - 如下所示:
var scriptEls = document.getElementsByTagName( 'script' );
var thisScriptEl = scriptEls[scriptEls.length - 1];
var scriptPath = thisScriptEl.src;
var scriptFolder = scriptPath.substr(0, scriptPath.lastIndexOf( '/' )+1 );
console.log( [scriptPath, scriptFolder] );
I tried this technique with 3 scripts loaded from different folders and get this output
我用从不同文件夹加载的 3 个脚本尝试了这种技术并获得了这个输出
/*
["http://127.0.0.1:8000/dfhdfh/folder1/script1.js", "http://127.0.0.1:8000/dfhdfh/folder1/"]
["http://127.0.0.1:8000/dfhdfh/folder2/script2.js", "http://127.0.0.1:8000/dfhdfh/folder2/"]
["http://127.0.0.1:8000/dfhdfh/folder3/script3.js", "http://127.0.0.1:8000/dfhdfh/folder3/"]
*/
* from John Resigs blog linked to above
* 来自上面链接的 John Resigs 博客
This means that when the script finally executes that it'll be the last script in the DOM - and even the last element in the DOM (the rest of the DOM is built incrementally as it hits more script tags, or until the end of the document).
这意味着当脚本最终执行时,它将成为 DOM 中的最后一个脚本——甚至是 DOM 中的最后一个元素(DOM 的其余部分是随着它点击更多脚本标签而逐渐构建的,或者直到文档)。
Update
更新
As pimvdb points out - this will work as the script is being evaluated. You will need to store the path somehow if you are going to use it later. You can't query the DOM at a later point. If you use the same snippet for each script the value of scriptFolder
will be overwritten for each script. You should give each script a unique variable perhaps?
正如 pimvdb 指出的那样 - 这将在评估脚本时起作用。如果您以后要使用它,则需要以某种方式存储路径。以后不能查询 DOM。如果您对每个脚本使用相同的代码片段,则每个脚本的值scriptFolder
都会被覆盖。你应该给每个脚本一个唯一的变量吗?
Wrapping your script in its own scope closes over the value of scriptFolder
making it available to the rest of the script without fear of being overwritten
将您的脚本包装在其自己的范围内可以关闭scriptFolder
使其可用于脚本的其余部分而不必担心被覆盖的价值
(function() {
var scriptEls = document.getElementsByTagName( 'script' );
var thisScriptEl = scriptEls[scriptEls.length - 1];
var scriptPath = thisScriptEl.src;
var scriptFolder = scriptPath.substr(0, scriptPath.lastIndexOf( '/' )+1 );
$( function(){
$('#my-div').click(function(e){
alert(scriptFolder);
});
});
})();
回答by John Slegers
Add the following code to your JS :
将以下代码添加到您的 JS 中:
var retrieveURL = function(filename) {
var scripts = document.getElementsByTagName('script');
if (scripts && scripts.length > 0) {
for (var i in scripts) {
if (scripts[i].src && scripts[i].src.match(new RegExp(filename+'\.js$'))) {
return scripts[i].src.replace(new RegExp('(.*)'+filename+'\.js$'), '');
}
}
}
};
Suppose these are the scripts called in your HTML :
假设这些是在您的 HTML 中调用的脚本:
<script src="assets/js/awesome.js"></script>
<script src="assets/js/oldcode/fancy-stuff.js"></script>
<script src="assets/js/jquery/cool-plugin.js"></script>
Then, you can use the function like this
然后,您可以像这样使用该功能
var awesomeURL = retrieveURL('awesome');
// result : 'assets/js/'
var awesomeURL = retrieveURL('fancy-stuff');
// result : 'assets/js/oldcode/'
var awesomeURL = retrieveURL('cool-plugin');
// result : 'assets/js/jquery/'
Note that this only works when there are no two script files in your HTML with the same name. If you have two scripts with the same name that are located in a different folder, the result will be unreliable.
请注意,这只适用于 HTML 中没有两个同名脚本文件的情况。如果您有两个位于不同文件夹中的同名脚本,结果将不可靠。
Note
笔记
If you dynamically add scripts to your page, you need to make sure your code is executed after the last script has been added to the DOM.
如果您将脚本动态添加到页面,则需要确保在将最后一个脚本添加到 DOM 之后执行您的代码。
The follow example shows how to do this with one dynamically loaded script. It outputs a JSON array with the src
link for scripts that load an external js file and a base64-encoded string of the JS content for inline scripts:
以下示例显示了如何使用一个动态加载的脚本来执行此操作。它输出一个 JSON 数组,其中src
包含加载外部 js 文件的脚本链接和内联脚本的 JS 内容的 base64 编码字符串:
var addScript = function(src, callback) {
var s = document.createElement( 'script' );
s.setAttribute( 'src', src );
document.body.appendChild( s );
s.onload = callback;
}
var retrieveURL = function(filename) {
var scripts = document.getElementsByTagName('script');
if (scripts && scripts.length > 0) {
for (var i in scripts) {
if (scripts[i].src && scripts[i].src.match(new RegExp(filename+'\.js$'))) {
return scripts[i].src.replace(new RegExp('(.*)'+filename+'\.js$'), '');
}
}
}
};
addScript('https://code.jquery.com/jquery-1.12.4.min.js', function() {
var scripts = document.getElementsByTagName('script');
var sources = [];
for (var i = 0; i < scripts.length; i++) {
if(scripts[i].src == '') {
sources.push(btoa(scripts[i].innerHTML));
} else {
sources.push(scripts[i].src);
}
}
document.body.innerHTML += '<pre>' + JSON.stringify(sources,null,2) + '</pre>';
});
See also this Fiddle.
另请参阅此 Fiddle。
回答by Marco Demaio
I don't think jQuery provide such a functionality. Anyway you can get currentc script path path (both fully http and relative) by reading the answer here: What is my script src URL?
我不认为 jQuery 提供这样的功能。无论如何,您可以通过阅读此处的答案来获取 currentc 脚本路径路径(完全 http 和相对路径):What is my script src URL?
回答by grilix
Can't you set a kind of path variable in the js? So, you save the path of the file in the file itself. For example:
你不能在js中设置一种路径变量吗?因此,您将文件的路径保存在文件本身中。例如:
$(function() {
var FilePath = "js/some/path";
setMyDynamicImageUsingPath(FilePath);
});
// ...
function setMyDynamicImageUsingPath(path) {
$("somediv").css("background-image", "url(" + path + "/images/img.png)");
}