【问题标题】:How to get the element that fired the "onclick" event如何获取触发“onclick”事件的元素
【发布时间】:2011-08-06 23:39:06
【问题描述】:
<script>
    function clicky(e){
        console.log(e)       //the clicked element
    }
</script>
<span onClick="clicky(this)">Clickable</span>

在上面的脚本中,console.log(e) 会给我我点击的&lt;span&gt;
有什么方法可以省略 clicky(this) 并仍然得到元素?
这是因为我不想将(this) 放在整个文档中。
欢迎任何答案。

【问题讨论】:

    标签: javascript google-chrome google-chrome-extension dom-events


    【解决方案1】:

    看这个:

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <title>Test</title>
      </head>
      <body>
        <div id="foo" style="background:blue; width:100px; height:100px">
        <script>
          function clicky(e){
            console.log(e); 
          }
          var foo = document.getElementById("foo");
          foo.onclick = function(e){clicky((e || window.event).target);}
        </script>
      </body>
    </html>
    

    【讨论】:

    • 它适用于 IE、Opera 和 Google Chrome。我认为它也适用于 Firefox,但现在我发现它没有。
    • 我想写一些这样的,但你更快。真的。 :> 无论如何,谢谢,现在一切正常。 :)
    • 这已经足够好了,因为我在 Google Chrome 扩展程序中使用它。谢谢。
    【解决方案2】:

    你可以试试这个,虽然没有测试。

    var spans = document.getElementsByTagName('span');
    spans.attachEvent('click'.'clicky');
    
     function clicky(e){
            console.log(e)       //the clicked element
        }
    

     var spans = document.getElementsByTagName('span');
    for (i in spans)
    {
        spans[i].attachEvent('click'.'clicky');
    }
    
         function clicky(e){
                console.log(e)       //the clicked element
            }
    

    【讨论】:

      【解决方案3】:
      function clicky(e, elem){
      
      <span onClick="clicky(event, this)">Clickable</span>
      

      【讨论】:

        【解决方案4】:

        或者您可以使用 Prototype 或 jQuery 或任何其他库。我会改善你的生活。

        【讨论】:

          猜你喜欢
          • 2011-08-29
          • 2016-06-23
          • 1970-01-01
          • 2017-04-12
          • 2010-09-08
          • 2014-11-01
          • 2010-11-02
          • 1970-01-01
          • 2013-12-28
          相关资源
          最近更新 更多