JQuery表选择最接近的空

时间:2016-03-18 10:47:33

标签: javascript jquery

我正在尝试选择一个来自同一个表(和行)的类 如果用户点击“删除”,我需要从“form_delete_id”中获取文本 不幸的是我回来了一个空字符串。没有运气我试过“最近()”和“父()” 这是我的代码:

<table class="responsive-table bordered striped">
  <thead>
    <tr>
      <th>id</th>
      <th>page</th>
      <th>parameter</th>
      <th>method</th>
      <th>Action</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td class="form_delete_id">2</td>
      <td class="form_delete_page">dqfsq</td>
      <td class="form_delete_parameter">qsdfqs</td>
      <td class="form_delete_method">post</td>
      <td class="form_delete_trigger"><a class="waves-effect waves-light btn red"><i class="material-icons left">delete</i>Remove</a></td>
    </tr>
  </tbody>
</table>

下面的Javascript:

<script>
$(".form_delete_trigger").click(function() {
  alert($(this).closest(".form_delete_id").text());
});
</script>

我的代码也可以在JSFIDDLE

找到

2 个答案:

答案 0 :(得分:6)

.form_delete_id是点击.form_delete_id的兄弟元素。您需要使用.siblings()代替.closest()

$(function(){
 $(".form_delete_trigger").click(function() {
  alert($(this).siblings(".form_delete_id").text());
 });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="responsive-table bordered striped">
  <thead>
    <tr>
      <th>id</th>
      <th>page</th>
      <th>parameter</th>
      <th>method</th>
      <th>Action</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td class="form_delete_id">2</td>
      <td class="form_delete_page">dqfsq</td>
      <td class="form_delete_parameter">qsdfqs</td>
      <td class="form_delete_method">post</td>
      <td class="form_delete_trigger"><a class="waves-effect waves-light btn red"><i class="material-icons left">delete</i>Remove</a></td>
    </tr>
  </tbody>
</table>

答案 1 :(得分:1)

尝试获取父级并在其中搜索删除ID:

<script>
$(".form_delete_trigger").click(function() {
  alert($(this).parent().find(".form_delete_id").text());
});
</script>

或使用sibiling

<script>
$(".form_delete_trigger").click(function() {
  alert($(this).siblings(".form_delete_id").text());
});
</script>

https://jsfiddle.net/t8okf8kc/