繁体   English   中英

在JavaScript中,我能否掌握脚本所在的节点?

[英]In JavaScript, can I get hold of the node that script is enclosed in?

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

谢谢。

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

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

首先,您说您遇到了IE8问题。 我的建议:使用类似jQuery的Javascript库为您处理所有这些特定于浏览器的陷阱。

然后,您有一些带有脚本的div,而您不想给div或脚本唯一的ID。 尽管如此,您仍然必须在div中放入seomthing才能调用该函数。 我的建议:改用类。

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

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

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

使用$(“。callFn1”)选择包含类“ callFn1”的所有元素。.each迭代所有选定的元素并调用函数。 该函数使用参数this调用fn1-它为您提供了当前正在处理的元素。 您现在所要做的就是修改函数fn1,如下所示:

function fn1(x)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM