[英]Ajax get table value based on row
我可以從行中獲取第一個和最后一個值,但不能獲取行中的第二個和第三個值。 誰能幫我。
這是我的代碼
=> HTML
<tr>
<td>one</td>
<td>two</td>
<td>three</td>
<td>four</td>
<td><button class="btnDelete">Delete</button></td>
</tr>
=> JavaScript
$(".btnDelete").click(function (evt) {
var cell=$(evt.target).closest("tr").children().first();
var cell2=$(evt.target).closest("tr").children().last();
var custID=cell.text();
var custID2=cell2.text();
alert(custID);
alert(custID2);
}
謝謝 。
使用nth-child(n)
方法
例
$(".btnDelete").click(function (evt) { var cell2 = $(evt.target).parent().parent("tr").find("td:nth-child(2)").text(); var cell3 = $(evt.target).parent().parent("tr").find("td:nth-child(3)").text(); console.log("cell 2 : "+cell2+", cell 3 : "+cell3); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr> <td>one</td> <td>two</td> <td>three</td> <td>four</td> <td><button class="btnDelete">Delete</button></td> </tr> </table>
您可以使用eq(index)
通過其索引從td
獲取值。 Index
從0
開始
alert($(evt.target).closest("tr").children('td:eq(2)').text()); //get value from 3rd `td`
$("#myTable").on('click','.btnDelete',function(){
// get the current row
var currentRow=$(this).closest("tr");
var col1=currentRow.find("td:eq(0)").text(); // get current row 1st TD value
var col2=currentRow.find("td:eq(1)").text(); // get current row 2nd TD
var col3=currentRow.find("td:eq(2)").text(); // get current row 3rd TD
var data=col1+"\n"+col2+"\n"+col3;
alert(data);
});
如果要在div中獲取特定元素,則可以使用classname這樣做
$("#myTable").on('click','.btnDelete',function(){
// get the current row
var currentRow=$(this).closest("tr");
var col1=currentRow.find(".classOne").html(); // get current row 1st table cell TD value
var col2=currentRow.find(".classTwo").html(); // get current row 2nd table cell TD value
var col3=currentRow.find(".classThree").html(); // get current row 3rd table cell TD value
var data=col1+"\n"+col2+"\n"+col3;
alert(data);
});
如果要訪問每個表數據,只需遍歷td即可。
var cells = [];
$(evt.target).closest("tr").children().each(function(key, cell){
cells.push(cell);
alert($(cell).text());
});
附帶一提,您可以將evt.target
替換this
我認為在沒有jQuery的情況下獲取此值會更容易。 通過使用HTMLTableRowElement.cells DOM屬性。 這幾乎就像一個數組,而不是一個數組。
$("#myTable").on('click','.btnDelete',function(){
// get the current row
var currentRow = $(this).closest("tr")[0];
var cells = currentRow.cells;
var firstCell = cells[0].textContent;
var secondCell = cells[1].textContent;
//...
//nthCell = cells[n-1].textContent;
console.log( firstCell );
console.log( secondCell );
});
如果你仍然想jQuery的,然后代替.first()
和.last()
方法,你可以使用.eq()
方法。
var rowCells = $(this).closest("tr").children();
var firstCell = rowCells.eq( 0 ).text();
var secondCell = rowCells.eq( 1 ).text();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.