[英]how to access table row object from an anchor within a cell?
我有幾行的桌子。 我想訪問與觸發函數populateRow()的錨在同一行中的值的單元格; (我希望我能清楚地解釋它)。 知道怎么做嗎?
<tr>
<td>
some value
</td>
<td>
<a href="#myPopup" data-rel="popup" class="ui-btn ui-btn-inline ui-corner-all ui-icon-check ui-btn-icon-left" onclick="populateRow();">update</a>
</td>
</tr>
<tr>
<td>
another value
</td>
<td>
<a href="#myPopup" data-rel="popup" class="ui-btn ui-btn-inline ui-corner-all ui-icon-check ui-btn-icon-left" onclick="populateRow();">update</a>
</td>
</tr>
該populateRow()
函數需要知道單擊的錨,所以你需要或者通過this
把它給它所述錨定器的參考:
onclick="populateRow(this);"
function populateRow(anchor) {
var row = $(anchor).closest("tr");
var firstCellValue = row.find("td").first().text();
}
...然后從那里使用.closest()
將DOM向上導航到包含tr的元素。
或者,最好將click事件處理程序與jQuery綁定,而不是將其內聯到每一行中:
$(document).ready(function() { $("#idOfYourTable").on("click", "a", function(e) { var row = $(this).closest("tr"); var firstCellValue = row.find("td").first().text(); console.log(firstCellValue); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <table id="idOfYourTable"> <tr> <td>Value 1</td> <td> <a href="#myPopup" data-rel="popup" class="ui-btn ui-btn-inline ui-corner-all ui-icon-check ui-btn-icon-left">update</a> </td> </tr> <tr> <td>Value 2</td> <td> <a href="#myPopup" data-rel="popup" class="ui-btn ui-btn-inline ui-corner-all ui-icon-check ui-btn-icon-left">update</a> </td> </tr> </table>
(單擊“運行...”按鈕以查看其工作。)
我不知道populateRow()
函數的作用是什么,但是如果您想在同一tr
的第一個td
上獲取值,則可以嘗試測試一下:
的onclick = “警報($(本).closest( 'TR')找到( 'TD:第一'。)文本())”
如果要在populateRow()
函數中傳遞它,則可以:
的onclick = “populateRow($(本).closest( 'TR')找到( 'TD:第一'。)文本())”
或者...如果您傳遞該元素,然后稍后在您的函數中對其進行處理,則會更加整潔:
的onclick = “populateRow(這)”
function populateRow(elm) {
var val = $(elm).closest('tr').find('td:first').text();
alert(val);
}
希望這可以幫助。 祝好運!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.