App*_*eer 8 javascript jquery jquery-selectors
有人知道是否有可能在没有任何其他选择器定义的情况下用jQuery选择当前的脚本标签?
<script type="text/javascript">
$(document).ready( function(){
// Here i need to select the current tag "<script ..."
})
</script>
Run Code Online (Sandbox Code Playgroud)
在文档就绪方法之外,只需$('script').last();:
<script type="text/javascript">
var currentScript = $('script').last();
$(document).ready( function(){
//Use the variable currentScript here
})
</script>
Run Code Online (Sandbox Code Playgroud)
或者只是给你的脚本一个id.
实现这一目标的最可靠方法是:
<script>
(function(script){
//do whatever you want with script here...
})(document.currentScript);
</script>
Run Code Online (Sandbox Code Playgroud)
它比其他解决方案更强大,因为您也可以在文档加载后使用它。此外,它不需要定义变量(如果您有多个脚本标签,这可能是一个问题,因为您不能重用相同的变量名称)。使用 JQuery:
<script>
(function(script){
$(document).ready(function(){
// do whatever you want after the DOM as loaded here...
});
})(document.currentScript);
</script>
Run Code Online (Sandbox Code Playgroud)
小智 5
我认为这是最快的方式
<script type="text/javascript">
var scripts = document.getElementsByTagName("script");
var thisScript = scripts[scripts.length - 1];
</script>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5029 次 |
| 最近记录: |