【发布时间】:2011-01-05 13:21:20
【问题描述】:
在 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 child element is closed (KB927917)”,我怀疑它可能是因为我正在使用 appendChild 将图像附加到 body 元素并且 body 元素没有关闭。知识库文章建议添加到直接父级(即使该标记显然没有关闭)可以解决问题。
谢谢。
【问题讨论】:
标签: javascript parent appendchild