获取对 <script> 的引用父元素 [英] Obtain a reference to <script> parent element
问题描述
我有一个类似的问题,比如在这里但是而不是获取父 id,如何获得对脚本父的引用,而不必为脚本标记编写 id?
例如,我将以下代码注入网站:
一些其他的 html 标签<script src="http://path_to_my_script.js"></script>
我需要的是,在我的 path_to_my_script.js
文件中,我可以获得对外部 div
的引用.
有一个问题,就是代码会被复制粘贴在同一个网页的多个地方,这使得标识符变得毫无用处.
有没有机会在整个代码中不编码 id 的情况下做到这一点?
如果解决方案是使用 jQuery 就更好:D
提前致谢.
如 Javascript中的当前元素是什么?,当前元素也是最后一个
元素,执行时.
答案也适用于您的情况,因为外部脚本的加载不会延迟(通过 async
或 defer
属性).
var scriptTag = document.getElementsByTagName('script');scriptTag = scriptTag[scriptTag.length - 1];var parentTag = scriptTag.parentNode;
大多数浏览器(甚至 IE6)都支持 document.scripts
.Firefox 从版本 9 开始支持此对象.因此,也可以使用以下代码:
var scriptTag = document.scripts[document.scripts.length - 1];var parentTag = scriptTag.parentNode;
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>
What I need is that in my path_to_my_script.js
file I can get a reference to the outer div
.
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.
There is any chance to do that without to code an id in the entire code?
If the solution is with jQuery the better :D
Thanks in advance.
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.
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;
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;
这篇关于获取对 <script> 的引用父元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!