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 Parsing Error: Unable to modify the parent container element before the child element is closed (KB927917)”我怀疑这可能是因为我使用 appendChild 将图像附加到 body 元素并且 body 元素未关闭。知识库文章建议添加到直接父级(即使该标记显然没有关闭)可以解决问题。
谢谢。