简体   繁体   English

如何获取触发“ onclick”事件的元素

[英]How to get the element that fired the “onclick” event

<script>
    function clicky(e){
        console.log(e)       //the clicked element
    }
</script>
<span onClick="clicky(this)">Clickable</span>

In the script above, the console.log(e) will give me the <span> that I clicked on. 在上面的脚本中, console.log(e)将给我单击的<span>
Is there any way that I could omit the clicky( this ) and still get the element? 有什么办法可以省略clicky( this )并仍然获取元素?
It's because I don't want to put (this) all over the document. 这是因为我不想在整个文档中放(this)
Any answer are welcomed. 任何答案都欢迎。

See this: 看到这个:

<!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>

You could try this, not tested though. 您可以尝试此方法,但未经测试。

var spans = document.getElementsByTagName('span');
spans.attachEvent('click'.'clicky');

 function clicky(e){
        console.log(e)       //the clicked element
    }

or 要么

 var spans = document.getElementsByTagName('span');
for (i in spans)
{
    spans[i].attachEvent('click'.'clicky');
}

     function clicky(e){
            console.log(e)       //the clicked element
        }
function clicky(e, elem){

<span onClick="clicky(event, this)">Clickable</span>

Or you could use Prototype or jQuery or any other library. 或者,您可以使用Prototype或jQuery或任何其他库。 I would improve your life. 我会改善你的生活。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM