Rails3jQuery:如何提醒td的id

Rails 3 jQuery : How to alert id of td

本文关键字:id td 何提醒 Rails3jQuery      更新时间:2023-09-26

我有一个3x3的td表,每个表都有id(id='a1'…id='c3')。我希望能够点击9个td中的任何一个,并提醒该td的id。

这是我的Coffeescapet(在资产管道中)

$(document).ready ->
$("td").click ->
    alert(#I would like to alert the id of whichever of the 9 td cell's have been clicked on)

这是我的index.html.erb

<table>
 <tbody>
  <tr>
   <td id='a1'>A1</td>
   <td id='b1'>B1</td>
   <td id='c1'>C1</td>
  </tr>
  <tr>
   <td id='a2'>A2</td>
   <td id='b2'>B2</td>
   <td id='c2'>C2</td>
  </tr>
  <tr>
   <td id='a3'>A3</td>
   <td id='b3'>B3</td>
   <td id='c3'>C3</td>
  </tr>
 </tbody>
</table>

我在JS很糟糕,所以任何帮助都很感激!

$('td').click: (e)->
  alert $(@).id

CoffeeScript 中相同

此外,使用data-*属性,使用html元素存储用户数据非常容易,例如:

<td data-id="42"></td>

使用jQuery数据方法很容易获得这个id,如下所示:

var id = $('td').data('id');

首先,在上使用jQuery比在每个td上附加一个click处理程序产生更好的性能,尤其是当您有很多td时:

$('table').on 'click', 'td', (event) ->
  # event.currentTarget is the td which was clicked
  alert event.currentTarget.id

event.currentTarget将是一个DOM元素对象,因此每个属性都可以作为对象的属性使用。引用$(this).id的其他答案是错误的,因为$(this)(或$(event.currentTarget))是一个jQuery对象,因此attr方法可以使用这样的属性:$(this).attr('id')