1

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

谢谢。

4

2 回答 2

0

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

首先,您说您在使用 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)
于 2011-01-05T14:40:28.427 回答
0

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

于 2011-01-05T14:33:48.797 回答