2012-11-07 135 views

回答

37

您可以在調查收集腳本:

var scripts = document.getElementsByTagName("script"); 

對於返回scripts陣列中的每個元素,你可以訪問其src屬性。

當前正在執行的包含文件將始終是scripts陣列中的最後一個。所以你可以在scripts[scripts.length-1]訪問它。

當然這隻會在初始代碼運行的時候才起作用,例如在加載初始腳本後調用的函數中不會有用,所以如果您需要稍後可用的值,則需要保存它到一個變量。

+0

感謝,這正是我想要 – hguser

+0

如果我們已經包含多個文件,將它的工作...那麼每個js文件如何顯示它自己的src路徑.. ?? – xxbinxx

+0

值得注意的是,您可能想要使用另一種方法從'scripts'數組中獲取想要的腳本。我使用這種方法,但是有報道稱,在Firefox中每隔一段時間(blegh ...)就會有另一個腳本在我的邏輯抓取該元素數組的時候加載。 聰明的事情就是像最後3個那樣抓取並循環遍歷它們,並找到具有要查找的文件名的文件。 –

21

獲取的JavaScript文件

在Apache目錄將這個下的電流路徑/ tmp並將其稱爲test.html。訪問URL

localhost/grader/test.html?blah=2#foobar 

的Javascript:在位置的屬性

<html> 
<script> 
    alert(location.pathname); // /tmp/test.html 
    alert(location.hostname); // localhost 
    alert(location.search); // ?blah=2 
    alert(document.URL);  // http://localhost/tmp/test.html?blah=2#foobar 
    alert(location.href);  // http://localhost/tmp/test.html?blah=2#foobar 
    alert(location.protocol); // http: 
    alert(location.host);  // localhost 
    alert(location.origin); // http://localhost 
    alert(location.hash);  // #foobar 
</script>        
</html> 

的更多信息:​​

或者,如果您有jQuery的:

<html> 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"> 
</script> 
    $(location).attr('href');  // http://localhost/tmp/test.html?blah=2#foobar 
    $(location).attr('pathname'); // /tmp/test.html 
</script> 
</html> 
1

這將工作。但是,它要求您已經知道腳本的文件名是什麼。但在大多數情況下,你會知道這一點。

function absFileLoc(filename) { 
    var scriptElements = document.getElementsByTagName('script'); 
    for (var i = 0; i < scriptElements.length; i++) { 
    var source = scriptElements[i].src; 
    if (source.indexOf(filename) > -1) { 
     var location = source.substring(0, source.indexOf(filename)) + filename; 
     return location; 
    } 
    } 
    return false; 
} 
+0

這是一個獲取css文件絕對位置的函數。 https://gist.github.com/jamrizzi/44bac4240057b4a89a2d918d05680e3d – jamrizzi

-2

,如果你想獲得當前的文件名或目錄

location.href.split('/')[ location.href.split('/').length - 1 ];

+0

location.href獲取當前網頁的url,而不是當前正在執行的javascript文件。 – CpnCrunch

+0

我們首先得到的網址,比分裂它得到所需的部分。 location.href.split('/')[0]; //獲取第一部分 location.href.split('/')[location.href.split('/')。length - 1]; //獲取文件名 – Amr

+0

不,這是不正確的。您正在獲取頁面的網址,而不是當前的JavaScript文件。如果您將該JavaScript代碼放入www.def.com/page.html中的www.abc.com/file.js文件中,location.href將返回www.def.com/page.html。問題是如何獲取JavaScript文件的名稱,即www.abc.com/file.js。 – CpnCrunch

0

試試這個我知道這是一個老問題,但還是實際的,因爲IE瀏覽器仍然沒有提供腳本src。

最佳形式我是給script標籤的唯一ID:

<script id="kuvaScript" src="jscripts/kuva/kuva.min.js"></script> 

腳本我使用內部:

var thisScript = $("#kuvaScript").attr("src"); 
    var thisPath = thisScript.split('/').slice(0, -1).join('/')+'/'; 

它將保持SRC格式,因爲它是(相對或完成)並在IE和Chrome中進行測試。

希望它能爲您節省很多時間。

0

很容易

將這個在* js文件,你想要得到的路徑:

let scripts = document.getElementsByTagName('script') 
let lastScript = scripts[scripts.length -1] 
console.log('lastScript', lastScript.src)