【问题标题】:How to get a value of the closest td with class on button click?如何在按钮单击时获得最接近 td 的值?
【发布时间】:2013-12-18 01:55:39
【问题描述】:

我有带有数据和按钮的表格行。 http://codepen.io/leongaban/pen/nuIkd

每个按钮对应于每一行,当您单击按钮时,它会将类名从hide 更改为un_hide 下一步是检索具有类contact_name 在该行中的td 的文本值单击的按钮也属于。

表结构:

<tr>
  <td class="contact_name" style="padding: 7px 0;">
    Name 1
  </td>
  <td>
      <button class="btn_hide">Hide</button>
  </td>
</tr>
<tr>
  <td class="contact_name" style="padding: 7px 0;">
      Name 2
  </td>
  <td>
      <button class="btn_hide">Hide</button>
  </td>
</tr>

使用这个 jQuery,它将在所有行中获取 .contact_name 的所有文本值

var name = $('.contact_name').text();

所以我尝试这个来获取“最近的”.contact_name td 的文本值

var name = $(this).closest('.contact_name').text();

但是这对我来说返回空白:(

如何通过点击第一个隐藏按钮获得Name 1值?

【问题讨论】:

  • $(this).closest('td').siblings('.contact_name').text()

标签: javascript jquery html-table closest


【解决方案1】:

.contact_name 不是单击按钮的父级。

var name = $(this).closest('tr').find('.contact_name').text();

【讨论】:

    【解决方案2】:

    试试,

    var name = $(this).closest('td').prev('.contact_name').text();
    

    或者

    var name = $(this).closest('tr').find('.contact_name').text();
    

    DEMO

    【讨论】:

      【解决方案3】:
      var name = $(this).closest('tr').children('.contact_name').text();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-11
        • 1970-01-01
        • 1970-01-01
        • 2018-06-22
        • 2018-10-08
        • 2017-10-25
        • 2021-07-26
        • 1970-01-01
        相关资源
        最近更新 更多