如何找到被单击的元素的ID? [英] How do I find the ID of an element that was clicked?

查看:36
本文介绍了如何找到被单击的元素的ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有很多html元素,表中的一行由表数据(< td> )标记组成.

Say I have an many html elements, a row in a table composed of table data (<td>) tags.

<td id="data1">foo</td>
<td id="data2">bar</td>
<td id="data3">baz</td>

如何返回被点击的 td id .我知道我应该为它们建立链接,以便可以正确单击它们,但是仅在这种情况下,我不想放置链接.

How would I return the id of the td that was clicked. I know that I should make them links so that I can click on them properly, but just for this case I don't want to put links.

$("td").click(function () {
  id = //The ID finder goes here
  clickFunction(id)
 }

我当时在想这是如何格式化的.jQuery会将onclick事件侦听器附加到任何表数据标签上,并在触发时,将使用所单击的表数据元素的ID来运行一个函数.

I was thinking this is how it would be formatted. JQuery would attach an onclick event listener to any table data tags and when it fired, a function would run with the id of the table data element that was clicked.

推荐答案

简单地说, this.id :

$("td").click(function() {
  console.log(this.id)
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td id="data1">foo</td>
    <td id="data2">bar</td>
    <td id="data3">baz</td>
  </tr>
</table>

这篇关于如何找到被单击的元素的ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆