简体   繁体   中英

JQuery table select closest empty

I am trying to select a class which is from the same table (and row).
If the user clicks on "Remove", I need to grab the text from "form_delete_id".
Unfortunately I get an empty string back. I tried "closest()" and "parent()" without luck.
This is my code:

<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>

And the Javascript below it:

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

My code can also be found on JSFIDDLE

.form_delete_id is sibling element of clicked .form_delete_id .You need to use .siblings() instead of .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> 

Try getting the parent and searching it for the delete id:

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

or using sibiling

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

https://jsfiddle.net/t8okf8kc/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM