我有这样的代码:
<div>
<script type="text/javascript">
(function() {
var s = document.createElement('script');
s.type = 'text/javascript';
s.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'localhost/chat/logo.js');
var t = document.getElementById('craftysyntax');
t.appendChild(s, t);
})();
</script>
<div>
我希望由 async' 加载的文件能够做这样的事情(注意:这不是有效的 js 代码,但这是我想做的)
parent.appendChild(abc);
这将在父元素 div
中添加子元素 abc
。
那么,脚本有什么方法可以引用它的父容器吗?
编辑:
我为什么要这样做?
我的网站(在线商店)使用一个聊天程序,导航栏中的链接会根据是否有运算符(operator)登录聊天程序而变化。我正在尝试将程序转换为使用异步加载器,但如果已异步加载,外部js将无法使用document.write
。我正在尝试将脚本中的所有 document.write
调用转换为使用 dom。
最佳答案
当你的代码像那样立即执行时,最后一个 script
元素将是当前元素(因为同步下载和执行)。
因此您可以获得对所有 script
元素的引用,然后使用 length
属性减一来获取最后一个元素。
然后你可以通过parentNode
属性访问它的父节点。
<script type="text/javascript">
var allScripts = document.getElementsByTagName('script'),
thisScriptParent = allScripts[scripts.length - 1].parentNode;
</script>
jsFiddle .
此外,无需使用三元来检查 https
。只需使用无协议(protocol) (//localhost/chat/logo.js
),它将解析为父站点的协议(protocol)。
关于javascript - 获取javascript的周围元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6132220/