如何从自己的js文件中找到脚本路径

时间:2014-09-05 07:07:09

标签: javascript jquery

我想找到自己的js文件的脚本路径。

所以我想要一个字符串" C:\ files \ MyProject \ MyScripts \ MyJavaScript.js"。

这怎么可能?

6 个答案:

答案 0 :(得分:2)

你可以尝试(Jquery):

var myScriptDetails = $('script');

myScriptDetails将包含有关脚本的详细信息,包括其位置。

答案 1 :(得分:1)

试试这个解决方案。我想这正是你想要的:)

将此代码放在每个链接的脚本文件

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 );// you can save these in any variable also

我用这个HTML代码测试了它:

<!DOCTYPE html>
<html>
  <head> 
      <title>testing...</title>  
      <script type="text/javascript" src="test.js"></script> 
      <script type="text/javascript" src="js/test2.js"></script> 
      <script type="text/javascript" src="../test3.js"></script> 
    </head>  
    <body>
     content area
    </body>
</html>

在控制台中找到此输出:

file:///D:/workspace/dbshell/www/test.js  file:///D:/workspace/dbshell/www/          test.js:6
file:///D:/workspace/dbshell/www/js/test2.js  file:///D:/workspace/dbshell/www/js/   test2.js:6
file:///D:/workspace/dbshell/test3.js  file:///D:/workspace/dbshell/                 test3.js:6

特别感谢meouw .. 希望这会有所帮助..

答案 2 :(得分:0)

客户端无法访问物理路径。您可以获得src标记的script属性。

服务器端,您可以获得物理路径。例如(C#):

Path.GetFullPath(path)

答案 3 :(得分:0)

要在JavaScript中查找URL的完整路径,请使用此location.href

答案 4 :(得分:0)

如果可以将服务器的绝对路径定义为常量变量,

你可以通过从window.location.href进行投射来实现。从window.location.host中删除主机前缀window.location.href,并使用服务器的绝对路径预删除。

尝试:

 console.log(window.location.href);

答案 5 :(得分:0)

这是我如何做到的:

function ScriptPath() {
  var scriptPath = '';
  try {
    //Throw an error to generate a stack trace
    throw new Error();
  }
  catch(e) {
    //Split the stack trace into each line
    var stackLines = e.stack.split('\n');
    var callerIndex = 0;
    //Now walk though each line until we find a path reference
    for(var i in stackLines){
      if(!stackLines[i].match(/http[s]?:\/\//)) continue;
      //We skipped all the lines with out an http so we now have a script reference
      //This one is the class constructor, the next is the getScriptPath() call
      //The one after that is the user code requesting the path info (so offset by 2)
      callerIndex = Number(i) + 2;
      break;
    }
    //Now parse the string for each section we want to return
    pathParts = stackLines[callerIndex].match(/((http[s]?:\/\/.+\/)([^\/]+\.js)):/);
  }

  this.fullPath = function() {
    return pathParts[1];
  };

  this.path = function() {
    return pathParts[2];
  };

  this.file = function() {
    return pathParts[3];
  };

  this.fileNoExt = function() {
    var parts = this.file().split('.');
    parts.length = parts.length != 1 ? parts.length - 1 : 1;
    return parts.join('.');
  };
}