JavaScript 有没有办法在脚本标签上没有 id 属性的情况下获取当前正在执行的脚本节点的父节点?
为了说明我的意思,如果我想将一个 img 附加到文档中,并且我想将该图像附加到 id 为“div1_id”的 div 节点,我可以在不知道 div 的 id 的情况下执行此操作吗?必须将 id="_scriptid"属性添加到脚本标记,就像我下面必须做的那样?
<script type="text/javascript">
function fn1()
{
var my_img = document.createElement("img");
var t = document.getElementById("_scriptid");
if (t.parentNode) {
t.parentNode.appendChild(my_img);
} else {
document.getElementsByTagName("body")[0].appendChild(my_img);
}
}
</script>
<div id="_div1_id" name="_div1_name">
<script type="text/javascript" id="_scriptid">
fn1();
</script>
</div>
这就是我想做的:
<head>
<script type="text/javascript">
function fn1()
{
var my_img = document.createElement("img");
var x = get the node that is the parent node of the current script tag,
and so that I can still separate this code out into a function
as shown here, I do not want the <head> tag returned, I want to
get the parent node of the script that called this function, i.e.
the node commented as "div1" below.
x.appendChild(my_img);
}
</script>
</head>
<div> <!-- div1 -->
<script type="text/javascript">
// Call a function to add an image to the enclosing node (div node in this example):
fn1();
</script>
</div>
我问的原因是有人告诉我他们在 IE8 中遇到错误“HTML 解析错误:无法在子元素关闭之前修改父容器元素 (KB927917)”,我怀疑可能是因为我使用appendChild将图像附加到body元素并且body元素没有关闭。知识库文章建议添加到直接父级(即使该标记显然未关闭)可以解决该问题。
谢谢。
最佳答案
尝试将代码分配给函数,然后将其分配给 window.onload 变量
关于javascript - 在 JavaScript 中,我可以获取包含脚本的节点吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4604455/