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

时间:2011-08-06 23:39:07

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

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

在上面的脚本中,console.log(e)会向我提供我点击的<span>
有没有办法可以省略clicky( this )并仍然可以获取元素?
这是因为我不想把(this)全部放在文件上 欢迎任何答案。

4 个答案:

答案 0 :(得分:3)

见:

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

答案 1 :(得分:0)

你可以尝试这个,但不测试。

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
        }

答案 2 :(得分:0)

function clicky(e, elem){

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

答案 3 :(得分:0)

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