Finding which element is clicked in the DOM

前端 未结 3 809
迷失自我
迷失自我 2021-01-03 14:08

The question was asked to me in an interview.

How to find which element is clicked by the user in the DOM using JQuery or Javascript or Both?

NOTE: User can

相关标签:
3条回答
  • 2021-01-03 14:17

    event.target sounds like what you're after.

    $('#id').click(function(e) {
        //e.target will be the dom element that was clicked on
    });
    
    0 讨论(0)
  • 2021-01-03 14:35

    Update for 2019. IE does not exist anymore, Edge goes chromium and JQuery is falling out of favour.

    To determine the clicked element, simply do:

    document.onclick = e => {
    
        console.log(e.target); 
    }
    
    0 讨论(0)
  • 2021-01-03 14:39

    Pure javascript:

    <script> 
      document.onclick = function(evt) {
        var evt=window.event || evt; // window.event for IE
        if (!evt.target) evt.target=evt.srcElement; // extend target property for IE
        alert(evt.target); // target is clicked
      }
    </script>
    
    0 讨论(0)
提交回复
热议问题