簡體   English   中英

如何從表tr td獲取值

[英]How to get a value from a table tr td

我的html文件中有此代碼

{% for dimension in dimension_list %}
<tr>
  <td>{{dimension.title}}</td>
  <td>{{dimension.description}}</td>
  <div class="button-group">
    <td><button type="button" class="delete btn" id="btn-confirm-del" ><i class="fa fa-trash"></i></button></td>
  </div>
</tr>       
{% endfor %}

當用戶單擊按鈕#btn-confirm-del時,如何獲取dimension.title的值?

我想以模態展示它。

您可以在jQuery中使用最接近的方法

 $('.delete').on('click', function(){ var dTitle = $(this).closest('tr').find('td:first-child').text() alert(dTitle); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr> <td>{{dimension.title}}</td> <td>{{dimension.description}}</td> <td> <div class="button-group"> <button type="button" class="delete btn" >delete<i class="fa fa-trash"></i></button> </div> </td> </tr> <tr> <td>{{dimension.title}}</td> <td>{{dimension.description}}</td> <td> <div class="button-group"> <button type="button" class="delete btn" >delete<i class="fa fa-trash"></i></button> </div> </td> </tr> </table> 

我希望這能幫到您

您可以嘗試以下方法:

$('.btn.delete').on('click', function(event){
     $(event.currentTarget).closest('tr').children('td').first().text();
});

這將獲得最接近按鈕的<tr> ,然后從第一個<td>內部獲取值

為了避免在循環中玩id ,我更喜歡以下內容(在本機JS中)

將按鈕更改為:

<button type="button" class="delete btn"  onclick="delete(event)"><i class="fa fa-trash"></i></button>

在JS部分中捕獲該按鈕,如下所示:

function delete(event) {
 console.log(
   (event.currentTarget)
   .parentElement
   .parentElement
   .parentElement
   .childNodes[0]
   .innerHTML)
}

您可以使用這樣的東西:

{% for dimension in dimension_list %}
<tr>
  <td id="{{dimension.id}}">{{dimension.title}}</td>
  <td>{{dimension.description}}</td>
  <div class="button-group">
    <td><button type="button" class="delete btn" onclick="get_title(\'' +{{dimension.id}}+ '\',\'' +{{dimension.title}}+ '\');"  ><i class="fa fa-trash"></i></button></td>
  </div>
</tr>       
{% endfor %}

JS部分:

function get_title(id,title){
  var title = $("#"+id).text();
  console.log(title);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM