在JavaScript中,我可以获取脚本所包含的节点吗?

时间:2011-01-05 13:21:20

标签: javascript parent appendchild

在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元素未关闭。知识库文章建议添加到直接父级(即使该标记显然未关闭)可以解决问题。

感谢。

2 个答案:

答案 0 :(得分:0)

尝试将代码分配给函数,然后将其分配给window.onload变量

答案 1 :(得分:0)

我认为问题的解决方案可能是重新思考问题。

首先,你说你遇到了IE8的问题。我的建议:使用像jQuery这样的Javascript库来处理所有特定于浏览器的陷阱。

然后,你有一些带有脚本的div,你不想给div或脚本提供唯一的id。尽管如此,你必须在你的div中放置一些东西来调用这个函数。我的建议:改用类。

<div class="callFn1"></div>

这有用吗? 与jQuery结合使用,可以为您提供以下解决方案:

$(".callFn1").each(
  function() {
    fn1(this);
  });

使用$(“。callFn1”),您可以选择包含“callFn1”类的所有元素,.each迭代所有选定元素并调用函数。此函数使用参数this调用fn1 - 它为您提供已处理的当前元素。你现在需要做的就是修改你的函数fn1有点像这样:

function fn1(x)