简体   繁体   中英

In the click event Jquery how is $(this)?

I have click event with jquery and i want to know how is selector clicked...

$('#parent').on('click','#child',function(){
 //....
});  


<div id="parent">
 <div id="child">
 </div>
</div>    

$(this) is #parent or #child ?

It's the child, why did you not just try

$('#parent').on('click','#child',function(){
    console.log($(this));
});  

 $('#parent').on('click','#child',function(){ console.log($(this)); });
 #child { width: 50px; height: 50px; cursor: pointer; background-color: orange; }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="parent"> <div id="child"></div> </div>

The context this is related to the event target. In your case is #child .

Further, you don't need event delegation when the id is available, so bind that event as follow:

$('#child').on('click',function(){
 //....
}); 

This is called Event delegation which allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

So, $(this) here is always referring to the clicked child element to a parent element, which here is #child .

A simple dynamically added element demo:

 // Attach Event // on(events, selector, handler); $('#container').on('click', 'a', function(event) { event.preventDefault(); console.log('Anchor clicked!'); alert('Anchor clicked!'); }); // Create elements dynamically $('#container').append('<a href="#output">Click me!</a>');
 body{font:12px Tahoma,Arial,Helvetica,sans-serif;color:#333;margin:20px} h1{font-size:1.4em;margin-bottom:20px} h2{font-size:1.2em} #container{border:1px dashed #aaa;font-size:1em;padding:10px} a{color:green}
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <h2>Dynamically added link:</h2> <div id="container"></div>

You could just write something like this to check.

 $(document).ready(function() { $('#parent').on('click','#child',function(){ console.log("This:", $(this)); }); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="parent"> Parent <div id="child"> CHILD (click on it) </div> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM