获取对< script>的引用父元素 [英] Obtain a reference to <script> parent element

查看:127
本文介绍了获取对< script>的引用父元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到类似的问题,例如此处而不是获取父ID,如何获得对脚本父级的引用而不必编写脚本标记的id?

I have a similar problem like posted here but instead of obtain the parent id, how Can I get a reference to the script parent without having to code an id for the script tag?

例如,我将以下代码注入网站:

For example, I have the following code injected to a website:

<div>
     some other html tags
     <script src="http://path_to_my_script.js"></script>
</div>

我需要的是我的 path_to_my_script.js 文件我可以获得对外部 div 的引用。

What I need is that in my path_to_my_script.js file I can get a reference to the outer div.

有一个catch并且是代码将被复制和粘贴在同一网页的多个位置,这使得标识符无用。

There is a catch and is that the code will be copied&pasted in several places in the same webpage, which makes an identifier useless.

如果没有在整个代码中编码id,有没有机会这样做?

There is any chance to do that without to code an id in the entire code?

如果解决方案用jQuery更好:D

If the solution is with jQuery the better :D

提前致谢。

推荐答案

Javascript中的当前元素是什么? ,当前< script> 元素也是最后一个< script> 元素,当时执行

As mentioned in What is the current element in Javascript?, the current <script> element is also the last <script> element, at the time of execution.

答案也适用于您的情况,因为外部脚本的加载不会延迟(通过 async 推迟属性)。

The answer also applies to your case, since the load of the external script is not deferred (through the async or defer attribute).

var scriptTag = document.getElementsByTagName('script');
scriptTag = scriptTag[scriptTag.length - 1];
var parentTag = scriptTag.parentNode;

大多数浏览器(甚至IE6)都支持 document.scripts 。从版本9开始,Firefox支持此对象。因此,也可以使用以下代码:

Most browsers (even IE6) support document.scripts. Firefox supports this object as of version 9. So, the following code can also be used:

var scriptTag = document.scripts[document.scripts.length - 1];
var parentTag = scriptTag.parentNode;

这篇关于获取对&lt; script&gt;的引用父元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆