我知道在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元素。
或者,您可以将
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()
会按需工作。