【问题标题】:Get the DOM element that calls Javascript without an event获取在没有事件的情况下调用 Javascript 的 DOM 元素
【发布时间】: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


【解决方案1】:

&lt;div&gt;“调用”脚本并不准确。脚本就在那里,恰好位于 &lt;div&gt; 元素内,但 JavaScript 运行时对此并不感兴趣。

你可以这样做:

<div>
  <script id='script1234'>
    var parentElement = document.getElementById('script1234').parentNode;
    drawChip(parentElement);
  </script>
</div>

【讨论】:

    【解决方案2】:

    试试这个::

    var scriptDIVs = $("div").has("script")
    

    希望这会有所帮助!

    【讨论】:

      【解决方案3】:

      尝试类似:

      <div id="myDiv">
        <script>drawChip(document.getElementById("myDiv") );</script>
      </div>
      

      【讨论】:

        猜你喜欢
        • 2020-03-30
        • 2018-12-07
        • 2014-06-01
        • 2011-03-28
        • 1970-01-01
        • 1970-01-01
        • 2023-03-12
        • 2020-11-23
        • 2012-12-30
        相关资源
        最近更新 更多