[英]Get td parent and tr child
我需要從第一個TD單擊按鈕獲取值“ TEST1”。 我嘗試使用Javascript,但無法正常工作。打印結果使我不確定。
<table style="width:100%">
<tr>
<td>TEST1</td>
<td>TEST2</td>
<td><button class='x' type='button' onclick='openindex()' >value='button'</button></td>
</tr>
</table>
這是我的Javascript函數,由於找不到最接近的Tr,但我的子屬性不起作用,所以我無法弄清楚自己在做什么
function openindex(){
var $row = $(this).closest("tr");
$tds = $row.find("td:nth-child(1)").value;
alert($tds);
}
您在沒有顯式上下文的情況下調用openindex()
,因此this
(在其內部)將是window
而不是元素。
您可以通過:
onclick="openindex.call(this)"
但您應該首先避免使用onclick
屬性,而應使用jQuery().on
綁定函數。
jQuery('button').on('click', openindex);
我想你只需要使用
$tds = $row.find("td:nth-child(1)").text();
代替
$tds = $row.find("td:nth-child(1)").value;
您還應該使用var關鍵字設置變量,以使其不是全局變量,並且由於它僅返回字符串,因此不需要$。
var tds = $row.find("td:nth-child(1)").text();
或者完全是另一種方式
$('.x').click(function () {
var $row = $(this).closest("tr");
var tds = $row.find('td').first().text();
alert(tds);
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.