【发布时间】:2013-06-27 17:25:55
【问题描述】:
我看过这些答案,但它们都在谈论(点击)事件:
Jquery: Select the element that called the function
Getting the ID of the element that fired an event
Get information of element that called function with jQuery
但是如果没有触发代码的事件呢?如果脚本在页面加载时已经位于 DOM 元素内怎么办:
<div>
<script>drawChip()</script>
</div>
如何获得对使用 jQuery 或 Javascript 调用此脚本的 div 元素的引用?我试过this,但没用。
【问题讨论】:
-
你可以给 div 一个 id
-
@MarcB 不会的。
-
@pointy:是的。手指跑在大脑前面。意识到这不是一个 onclick 处理程序。
-
快速简单的答案:不要把你的脚本放在那里!没有充分的理由。将所有脚本放在结束的正文标记内。将方法放置在 DOM 就绪的包装器中,并使用适当的选择器定位 div。
-
没有像 event.target.id 这样方便的自动获取方式。您可以将元素 id 作为参数传递给 drawChip 函数。\
标签: javascript jquery dom