查找函数调用的DOM位置

Find the DOM location of a function call

本文关键字:位置 DOM 函数调用 查找      更新时间:2023-09-26

我知道在Jquery中你可以得到事件。id,如果我触发了一个事件(点击等),但我如何获得一个简单的函数调用的DOM位置

,

<pre id="container2">...
  <script>
  FunctionCall();
  </script>
</pre>

我想从我的FunctionCall内部获得"container2"值

一般来说,脚本不知道它是从哪里启动的,所以没有通用的方法来执行您所要求的操作。您必须找到一个您事先知道的容器div,或者插入您自己的已知对象,然后您可以找到。

在您的特定示例中,可以这样做:

<pre id="container2">...
  <script>
  var fCntr = fCntr || 1;
  document.write('<div id="FunctionCallLocation' + fCntr + '"></div>');
  FunctionCall(fCntr++);
  </script>
</pre>

然后,在脚本中,您可以找到带有传递给它的id的DOM元素。

或者,您可以将document.write()放入函数本身,以便它标记自己的位置:

var fCntr = 1;
function FunctionCall() {
    var myLoc = "FunctionCallLocation" + fCntr++;
    document.write('<div id="' + myLoc + '"></div>');
    var myLoc = document.getElementById(myLoc);
}

如果FunctionCall只在页面加载时被调用,那么document.write()将按预期工作。

也许你可以尝试添加一个id或类的脚本元素。像这样:

<pre id='container2'>
    <script id='location'>
        (function FunctionCall() {
            var container2 = document.getElementById('location').parentNode;
            container2.appendChild(document.createElement('p'));
        }())
    </script>
</pre>