使用onclick函数获取点击的元素jquery

get the clicked element jquery with onclick function

本文关键字:元素 jquery onclick 函数 获取 使用      更新时间:2023-09-26

我有一个按钮:

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

我想在"action"函数中获取按钮("my button")的id。

我试着用

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

我试图从dom发送对象:

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

但它没有起作用。。。

我怎样才能拿到身份证?

您需要接受参数

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

但是,由于您正在使用jquery,我建议您使用它绑定事件

$(function() {
  $('#my-button').on('click', function() {
    alert(this.id);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="my-button" type="button">press me</button>

在jquery代码中设置onclick事件,现在所做的都是老式的,在少数浏览器中不推荐使用(许多在移动浏览器中)。

因此,从HTML元素中删除onlick事件的绑定,并添加jquery,如下所示。

$(function() { //document ready event
  $('#my-button').on('click',function() {
    var id = $(this).attr('id');
    alert(id);
  });
});
<script src="https://ajax.googleapis.com/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提供与事件相关联的元素,在您的情况下单击。

$(".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.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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