我知道在 Jquery 中,如果我触发了一个事件(点击等),您可以获得 event.id,但我将如何获得一个简单函数调用的 DOM 位置
前任 :
<pre id="container2">...
<script>
FunctionCall();
</script>
</pre>
我想从我的 FunctionCall 中获取“container2”值
我知道在 Jquery 中,如果我触发了一个事件(点击等),您可以获得 event.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 元素。
Or, you could put the document.write()
into the function itself so it marks its own location:
var fCntr = 1;
function FunctionCall() {
var myLoc = "FunctionCallLocation" + fCntr++;
document.write('<div id="' + myLoc + '"></div>');
var myLoc = document.getElementById(myLoc);
}
This exact code would only work if FunctionCall was only called at page load time so the document.write()
would work as desired.
也许您可以尝试将 id 或类添加到脚本元素。所以是这样的:
<pre id='container2'>
<script id='location'>
(function FunctionCall() {
var container2 = document.getElementById('location').parentNode;
container2.appendChild(document.createElement('p'));
}())
</script>
</pre>