[英]How to get value in a td by clicking its button
我試圖在單擊按鈕時在td中獲取值。 我使用下面的代碼,並且只獲得空白值。
所以我試圖更改css,以查看它是否選擇了特定的td。 然后
$(this).parents('tr td:nth-child(8)').css('color','red');
沒有工作,但
$(this).parents('tr').css('color','red');
工作並使該行數據全部變為紅色。 為什么這個 ?
第一個代碼示例的問題在於, td:nth-child(8)
不是this
引用元素的父級,而tr
是。
為了解決這個問題,您需要使用對parents()
和find()
單獨調用,如下所示:
$(this).parents('tr').find('td:nth-child(8)').css('color','red');
還要注意,假設您只想找到直接的tr
父元素,則可以用closest()
替換parents()
closest()
來稍微提高性能。
您可以使用.text()
來獲取被單擊的TD內的文本。
$('td').click(function(){ var num = $(this).text(); alert(num); });
table{border-collapse:collapse;} td{padding:5px;border:1px solid #ccc;} .here{background:yellow;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <table> <tr><td>Cell</td><td>Cell</td><td>Cell</td></tr> <tr><td>Cell</td><td>Cell</td><td class="here">8675309</td></tr> <tr><td>Cell</td><td>Cell</td><td>Cell</td></tr> </table>
如果在TD內也有要單擊的按鈕,則獲取與按鈕位置有關的所需文本:
$('#btnMyDiv').click(function(){ var num = $(this).closest('td').find('div').text(); alert(num); });
table{border-collapse:collapse;} td{padding:5px;border:1px solid #ccc;} .here{background:yellow;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <table> <tr><td>Cell</td><td>Cell</td><td>Cell</td></tr> <tr><td>Cell</td><td>Cell</td><td class="here"> <div id="myDiv">555-1212</div> <button id="btnMyDiv">Click Me</button> </td></tr> <tr><td>Cell</td><td>Cell</td><td>Cell</td></tr> </table>
這就是您如何從其他TD獲取數據的方法:
$('#btnMyDiv').click(function(){ var num = $(this).closest('tr').find('td:nth-of-type(2)').text(); alert(num); });
table{border-collapse:collapse;} td{padding:5px;border:1px solid #ccc;} .here{background:yellow;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <table> <tr><td>Cell</td><td>Cell</td><td>Cell</td></tr> <tr><td>Cell</td><td>YabaDabaDoo</td><td class="here"> <div id="myDiv">555-1212</div> <button id="btnMyDiv">Click Me</button> </td></tr> <tr><td>Cell</td><td>Cell</td><td>Cell</td></tr> </table>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.