【问题标题】:In JavaScript, can I get hold of the node that script is enclosed in?在 JavaScript 中,我可以获取包含脚本的节点吗?
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      首先,您说您在使用 IE8 时遇到了问题。我的建议:使用像 jQuery 这样的 Javascript 库来为您处理所有那些特定于浏览器的问题。

      然后,您有一些包含脚本的 div,并且您不想为 div 或脚本提供唯一的 ID。尽管如此,您必须将 seomthing 放入您的 div 中才能调用该函数。我的建议:改用类。

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

      这有什么用? 结合 jQuery,这为您的问题提供了以下解决方案:

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

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

      function fn1(x)
      

      【讨论】: