Javascript global onclick listener

前端 未结 3 1580
余生分开走
余生分开走 2020-12-31 07:39

Is there a way to register a global onclick listener that will fire anytime an element is clicked? Need to also get the id of that element.

相关标签:
3条回答
  • 2020-12-31 08:15
    document.addEventListener("click", function(evnt){
        console.log(evnt.target.id);
    });
    
    0 讨论(0)
  • 2020-12-31 08:15

    You can get id this way using javascript:

    window.onclick = function(event) {alert(event.target.id);}
    <div id="dID">div</div>
    <button id="bId">Button</button>
    
    <input type="text" id="txtId" class="txtclass" />

    0 讨论(0)
  • 2020-12-31 08:32

    Check this code, I haves used it in my live project for tracking users behaviour.

    document.addEventListener('click', (event)=> { 
        console.log('emitting click events');
    })
    
    document.addEventListener('dblclick',(event)=>{
        console.log('emitting double click events');
    } )
    
    document.addEventListener('contextmenu', (event)=>{
        console.log('emitting right click events');
    })
    
    document.addEventListener('mouseenter',(event)=> {
       console.log("mouse enter, hovering started")
    })
    
    document.addEventListener('mouseleave', (event)=> {
    console.log("hovering finished")
    })
    
    0 讨论(0)
提交回复
热议问题