簡體   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>

在上面的腳本中, 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或任何其他庫。 我會改善你的生活。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM