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

How to get the element that fired the "onclick" event

本文关键字:onclick 事件 元素 何获取 获取      更新时间:2023-09-26
<script>
    function clicky(e){
        console.log(e)       //the clicked element
    }
</script>
<span onClick="clicky(this)">Clickable</span>

在上面的脚本中,console.log(e)将给我点击的<span>。是否有任何方法,我可以省略clicky( this ),仍然得到元素?
这是因为我不想把(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>

你可以试试这个,但没有测试过。

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
        }
function clicky(e, elem){
<span onClick="clicky(event, this)">Clickable</span>

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