简体   繁体   中英

How to get DOM element in jQuery

I would like to get result that is clicked DOM element.

When I try below code, it return jQuery object.

my desired result is like this

<td>1</td> ← clicked DOM element

Are there any method to get this?

 jQuery($ => { $('td').on('click', function() { console.log($(this)); }) });
 td { padding:5px; border:solid black 1px;} table{ border-collapse:collapse;}
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <tr> <td>1</td> <td>2</td> <td>3</td> </tr> </table>

Just change $(this) to this

 jQuery($ => { $('td').on('click', function() { console.log(this); }) });
 td { padding:5px; border:solid black 1px;} table{ border-collapse:collapse;}
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <tr> <td>1</td> <td>2</td> <td>3</td> </tr> </table>

Just don't wrap this in JQuery.

 jQuery($ => { $('td').on('click', function() { console.log(this); }) });
 td { padding:5px; border:solid black 1px;} table{ border-collapse:collapse;}
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <tr> <td>1</td> <td>2</td> <td>3</td> </tr> </table>

You can try something like this:

 $(document).ready(function() { $('td').on('click', function() { /* your click event */ console.log("you clicked", this); }) });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <tr> <td>1</td> <td>2</td> <td>3</td> </tr> </table>

Just change console.log($(this)) to console.log(this) in your click event.

Because JQuery using only this not wrapped $(this) .

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