admin管理员组

文章数量:1291203

i have a button:

<button id="my-button" type="button" onclick="action()">press me</button>

i want to get the id of the button ("my-button"), in the "action" function.

i tried to get it with:

var id = $(this).id;
var id = $(this).attr('id');

i tried to send the object from the dom:

<button id="my-button" type="button" onclick="action(this)">press me</button>

and it didn't work...

how can i get the id?

i have a button:

<button id="my-button" type="button" onclick="action()">press me</button>

i want to get the id of the button ("my-button"), in the "action" function.

i tried to get it with:

var id = $(this).id;
var id = $(this).attr('id');

i tried to send the object from the dom:

<button id="my-button" type="button" onclick="action(this)">press me</button>

and it didn't work...

how can i get the id?

Share Improve this question asked Mar 23, 2016 at 8:05 johnnyjohnny 432 silver badges4 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 6

You need to accept the parameter

function action(elm) {
  alert(elm.id)
}
<button id="my-button" type="button" onclick="action(this)">press me</button>

However, as you are using jquery I would remend you to bind events using it.

$(function() {

  $('#my-button').on('click', function() {
    alert(this.id);
  });

});
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="my-button" type="button">press me</button>

Set the onclick event in your jquery code, Right now what ever is doing is old style, and is deprecated in few browsers (many in mobile browsers).

So remove the binding's of onlclick event from your HTML element and add in jquery as shown below.

$(function() { //document ready event

  $('#my-button').on('click',function() {
    var id = $(this).attr('id');
    alert(id);
  });

});
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="my-button" type="button">press me</button>

<button id="1" onClick="reply_click(this.id)">Button</button>

<script type="text/javascript">
function reply_click(clicked_id)
{
    alert(clicked_id);
}
</script>

event.target gives the element associated with the event, click in your case.

$(".btn-send").click((e)=>{ 
    $this = jQuery(e.target); // e.target gives element associated (targeted) with this event (click)
    console.log($this.data('id')); // loging data id for demo purpose
});
<script src="https://cdnjs.cloudflare./ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<input type="button" value="Send message" class="btn-send" data-id="40" />

本文标签: javascriptget the clicked element jquery with onclick functionStack Overflow