jQuery选择当前脚本标记

时间:2014-08-01 17:36:48

标签: javascript jquery jquery-selectors

有人知道是否有可能在没有任何其他选择器定义的情况下使用jQuery选择当前的script-tag?

<script type="text/javascript">
$(document).ready( function(){
    // Here i need to select the current tag "<script ..."
})
</script>

5 个答案:

答案 0 :(得分:8)

在文档就绪方法之外,只需执行$('script').last();

<script type="text/javascript">
var currentScript = $('script').last();
$(document).ready( function(){
    //Use the variable currentScript here
})
</script>

或者只是给你的剧本一个id。

答案 1 :(得分:3)

我认为这是最快的方式

<script type="text/javascript">
    var scripts = document.getElementsByTagName("script");
    var thisScript = scripts[scripts.length - 1];
</script>

答案 2 :(得分:3)

最可靠的方法是:

<script>
 (function(script){
    //do whatever you want with script here...
 })(document.currentScript);
</script>

它比其他解决方案更可靠,因为您还可以在文档加载后使用它。另外,它不需要定义变量(如果您有多个脚本标签,则可能会出现问题,因为您无法重复使用相同的变量名)。使用JQuery:

<script>
     (function(script){
        $(document).ready(function(){
            // do whatever you want after the DOM as loaded here...
        });
     })(document.currentScript);
</script>

答案 3 :(得分:0)

<script type="text/javascript">
  var currentScript = document.currentScript || (function() {
     var scripts = document.getElementsByTagName('script');
     return scripts[scripts.length - 1];
  })();
<script/>

document.currentScript适用于大多数浏览器,而scripts[scripts.length - 1]是其他浏览器的后备(可能会对<script async>施加一些限制)。

Further discussion

答案 4 :(得分:-1)

试试这个

var scripts = document.getElementsByTagName("script");
var thisScript = scripts[scripts.length - 1];