简体   繁体   中英

how to find the div id on mouse click in jquery?

I have multiple div in a webform and when i clicked on a particular div i need to perform some task based on the div id.

Is there any way to find the div id on mouse click?

 <table> <tr> <td> <div id="firstdiv">div1</div> </td> <td> <div id="seconddiv">div2</div> <td> <td> <div id="thriddiv">div3</div> </td> <td> <div id="fourthdiv">div4</div> </td> </tr> </table> 

Please try this:

$("table div").click(function() {
    var divID = this.id;//Or $(this).attr("id");
    //Your code here 
});

 $('div').click(function() { console.log($(this).attr('id')); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr> <td> <div id="firstdiv">div1</div> <td> <td> <div id="seconddiv">div2</div> <td> <td> <div id="thriddiv">div3</div> <td> <td> <div id="fourthdiv">div4</div> <td> <tr> <table> 

  • Bind click event over div element
  • this refers to clicked element in click-handler
  • Access id property of the element

 $('table div').on('click', function() { console.log(this.id); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <table> <tr> <td> <div id="firstdiv">div1</div> </td> <td> <div id="seconddiv">div2</div> </td> <td> <div id="thriddiv">div3</div> </td> <td> <div id="fourthdiv">div4</div> </td> </tr> </table> 

If you want to perform a function at the time to click on div, calling from the ID, this is the code:

<head>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

$(document).ready(function () {

  $('#firstdiv').click(function(){

    /*I add alert for the example, but here is where you put your code*/
     alert($(this).attr('id'));

});

</head>

<body>

<div id="firstdiv">div1</div>

</body>

In addition this is the information link with the function click () in jquery, has example of how to use it in different event on an element: https://api.jquery.com/click/

example calling the div inside table:

$("table div").click(function(){

   /*I add alert for the example, but here is where you put your code*/
   alert($(this).attr('id'));

}); 

Example calling with the tag div:

$('div').click(function() {

  /*I add alert for the example, but here is where you put your code*/
  alert($(this).attr('id'));

});

--body

<table>

<tr>

<td><div id="demo1"></td>

</tr>

</table>

And this is a post with good example: How can I get the ID of an element using jQuery?

Here is a simple yet effective answer

<div id="someId" onclick="somefunction(this.id)">
   Click me
</div>
<script>
  function somefunction(id){
    alert(id);
  }
</script>

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