参考脚本容器元素? [英] Reference script container element?

查看:33
本文介绍了参考脚本容器元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有一种方法可以获取其中包含脚本的DOM元素的句柄.所以如果我有:

I'm wondering if there is a way to get a handle on the DOM element that contains the script inside it. So if I had:

<script type="text/javascript> var x = ?; </script>

是否可以为"x"分配对包含"x"的脚本元素的引用?

Is there a way that I can assign "x" a reference to the script element that contains "x"?

推荐答案

您可以在script元素中包含一些标记文本,然后(类似于David所说的那样),您可以遍历所有 script 元素(使用 getElementsByTagName 或库的任何功能(如果使用的话)可能具有).那应该可靠地找到元素.看起来像这样(在线示例):

You could include some marker text in the script element, and then (similar to what David said), you can loop through all the script elements in the DOM (using getElementsByTagName or whatever features your library, if you're using one, may have). That should find the element reliably. That would look something like this (live example):

<body>
  <script id='first' type='text/javascript'>
    (function() {
      var x = "MARKER:first";
    })();
  </script>
  <script id='second' type='text/javascript'>
    (function() {
      var x = "MARKER:second";
    })();
  </script>
  <script id='third' type='text/javascript'>
    (function() {
      var x = "MARKER:third";
    })();
  </script>
  <script id='last' type='text/javascript'>
    (function() {
      var scripts, index, script;

      scripts = document.getElementsByTagName("script");
      for (index = 0; index < scripts.length; ++index) {
        script = scripts[index];
        if (script.innerHTML.indexOf("MARKER:second") >= 0
           && script.id !== "last") {
          display("Found MARKER:second in script tag #" + script.id);
        }
      }

      function display(msg) {
        var p = document.createElement('p');
        p.innerHTML = msg;
        document.body.appendChild(p);
      }
    })();
  </script>
</body>

请注意,就像上面的脚本一样,如果您要在不同脚本标签中寻找脚本标签标记,则需要进行处理.上面是通过检查script标记的ID处理的,但是您也可以将它分解成您不想找到的标记,例如(

Note that, like the script above, if you're looking for a script tag marker from within a different script tag, you'll need to handle that. Above it's handled by checking the ID of the script tag, but you can also just break it up in the one you don't want to find, like this (live example):

if (script.innerHTML.indexOf("MARKER:" + "second") >= 0) {
  display("Found MARKER:" + "second in script tag #" + script.id);
}

这篇关于参考脚本容器元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆