13

在后端生成 HTML 源代码,我使用单独的独立小部件。

我只是在生成的 HTML 输出中包含这样的标记。

 <div>
     I want to work with this DOM element
     <script>
          new Obj(/*but I can't get this <div> as a parameter! */);
     </script>
 </div>

我正在寻找一种方法来查找在其中obj创建的 DOM 元素(没有任何唯一 ID)。这将为我的应用程序增加灵活性并加快开发速度。但是在 JavaScript 中这在技术上是可能的吗?

4

4 回答 4

10

您可以在其中播种一个元素,然后获取它的父元素,然后删除该元素。

<div>
 I want to work with this DOM element
 <script>
      document.write("<div id='UniqueGUID_3477zZ7786_' style='display:none;'></div>");
      var thatDivYouWanted;
      (function(){
       var target = document.getElementById("UniqueGUID_3477zZ7786_");
       thatDivYouWanted = target.parentNode;
       target.parentNode.removeChild(target);
      })();
      new Obj(/*but I can't get this <div> as a parameter! */);
 </script>
</div>
于 2012-12-13T19:17:41.207 回答
6

The following code works:

<script>
  function Obj(color) {
    var scriptTags = document.getElementsByTagName("script");
    var scriptTag = scriptTags[scriptTags.length - 1];
    // find parent or do whatsoever
    var divTag = scriptTag.parentNode;
    divTag.style.backgroundColor = color;
  }
</script>


<div>
  I want to work with this DOM element
  <script>new Obj("green");</script>
</div>
<div>
  I want to work with this DOM element
  <script>new Obj("yellow");</script>
</div>
<div>
  I want to work with this DOM element
  <script>new Obj("lime");</script>
</div>

This method has very simple code and has almost zero impact on performance.

Note: I am pretty sure this won't work IE6 (as far as I remember it does not support manipulating open tags).

于 2012-12-13T19:21:19.753 回答
1

我相信你的方法并不理想。如果您尝试获取<div>,则应使用 JavaScript 和 API 以常规方式以编程方式完成,这些 API 使您能够查询目标<div>

您可以以受控方式(DOM Ready 然后 Query 然后 Your Method)在单独的范围内执行,而不是内联执行。您可以使用 ID、CSS 类名或 JavaScript 中的任何其他 CSS 选择器来定位您的 div。

这使您几乎可以在任何您想要的地方执行以下操作,而不是 inline

// on dom ready...
var div = document.getElementById('myDiv'), // replace with any other selector method
    myObject = new Object(div);

需要找到你的 div 吗?https://developer.mozilla.org/en-US/docs/DOM/Document.querySelectorAll

于 2012-12-13T19:23:36.097 回答
0

If you know beforehand how the page will be structured, you could use for example:

document.getElementsByTagName("div")[4]

to access the 5th div.

于 2012-12-13T19:20:24.687 回答