【问题标题】:Rails 3 jQuery : How to alert id of tdRails 3 jQuery:如何提醒 td 的 id
【发布时间】:2012-04-01 07:08:36
【问题描述】:

我有一个 3x3 的 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 方面很糟糕,所以感谢任何帮助!

【问题讨论】:

    标签: javascript html ruby-on-rails-3 jquery-ui coffeescript


    【解决方案1】:
    $('td').click: (e)->
      alert $(@).id
    

    CoffeeScript 中相同

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

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

    使用 jQuery data 方法可以轻松获取此 ID,如下所示:

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

    【讨论】:

    • 这让我找到了正确的方向,谢谢!这最终成为了有效的方法: $(document).ready -> $("td").click -> alert @id
    【解决方案2】:

    首先,使用jQuery on 比将click 处理程序附加到每个td 产生更好的性能,特别是如果您有很多tds:

    $('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')

    【讨论】:

    • 我正在调查这个问题。感谢您解释更好的方法!学习“最佳实践”或至少“更好的实践”总是好的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-18
    • 1970-01-01
    相关资源
    最近更新 更多