我有一个3x3的td表,每个td都有id (id='a1'...id='c3')。我希望能够点击9个td中的任何一个,并提醒该td的id。
这是我的Coffeescript (在资产管道中)
$(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做的很糟糕,所以任何帮助都是非常感谢的!
发布于 2012-03-16 02:03:15
$('td').click: (e)->
alert $(@).id在CoffeeScript中也是如此
此外,使用html元素存储用户数据非常容易,使用data-*属性,例如:
<td data-id="42"></td>使用jQuery data方法可以很容易地获得这个id,如下所示:
var id = $('td').data('id');发布于 2012-03-16 02:05:29
首先,与将click处理程序附加到每个td相比,使用jQuery on会产生更好的性能,特别是当您有很多td时:
$('table').on 'click', 'td', (event) ->
# event.currentTarget is the td which was clicked
alert event.currentTarget.idevent.currentTarget将是一个DOM元素对象,因此每个属性都将作为该对象的一个属性。提到$(this).id的其他答案是错误的,因为$(this) (或$(event.currentTarget))是一个jQuery对象,同样的属性也可以通过attr方法获得:$(this).attr('id')。
https://stackoverflow.com/questions/9725433
复制相似问题