....I also set the onlick event to window....">

How to get which item was clicked?

In my html , I have a simple div :

<div id="myDiv">
....

</div>

I also set the onlick event to window.clickas follows:

window.onclick = function()
{
    // do something
 }  

So, if I click somewhere in the div , how can I find that this click was made inside "myDiv"

Note. I can not add click event on my div, it is generated randomly from jqgrid

+4
source share
8 answers

I add this only to clarify the discussion with @Nishit Mahetarespect to my response to my vote.

- . " , div". , , !:)

jQuery, @erkaner . , .

$(document).on("click","#myDiv", function (event) {
     // Do something
});

:

  • jQuery. "" , , .
  • document.
  • , document , /.
  • . body , ( , ).
  • (click ) (.. ).
  • jQuery ( #myDiv) . .
  • , .

, ( ).

, ( 50 000 ), "" . .

onclick=

  • -, window.onclick - , - , ( , jQuery, ).
  • -, , onclick, ( , ). , jQuery , :)

:

, -, . , " div ", HTML :

$(document).on("click","table div", function (event) {
     // Do something
});

:

http://jsfiddle.net/TrueBlueAussie/eyo5Lnsy/

@Sashi Kant: HTML (, ), :)

+3
$(document).on("click","#myDiv", function (event) {
     alert(event.target.id);
});
+5

: window.onclick = function(event), , event.target:

window.onclick = function(event)
{
    alert(event.target);
}
+3

addEventListener - jQuery

document.getElementById('myDiv').addEventListener('click',function(e){
    // this div has been clicked
    console.log('this div has been clicked');
});

UPDATE

-jQuery-

document.addEventListener('click',function(e){
    if( e.target.id == 'myDiv' )
    {
        // this div has been clicked
        console.log('this div has been clicked');
    }
});
+3

var myDiv = document.getElementById('myDiv');

myDiv.style.cursor = 'pointer';
myDiv.onclick = function() {
    //DO SOMETHING
};
+1

.

$('body').click(function(e) {      
  if (e.target.id == 'myDiv') {
    alert('My Div!!!!');
  }
});​
+1
source

$( "body" ).click(function( event ) {
  $( "#log" ).html( "clicked: " + event.target.nodeName );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myDiv">
....

</div>
<div id="log"></div>
Run code
0
source

check the code below. check out demo

use event.target to get the clicked element.

window.onclick = function(event)
{
  if(event.target.id == "myDiv"){
    alert("here")
  }else{
    alert('Body')
  }
 console.log(event.target.id)
}  
0
source

All Articles