在 JavaScript 中不使用 length 屬性獲取節點列表中的最後一項?
假設下表是我們的表格 −
<table id="demo" border="1"> <tr> <td>John</td> </tr> <tr> <td>David</td> </tr> <tr> <td>Mike</td> </tr> </table> </body>
將以下內容與 text() 一起使用以獲取最後一項 −
$('table tr:last td')
示例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initialscale=1.0"> <title>Document</title> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> </head> <body> <table id="demo" border="1"> <tr> <td>John</td> </tr> <tr> <td>David</td> </tr> <tr> <td>Mike</td> </tr> </table> <script> var lastValue= $('table tr:last td').text(); console.log("The last value is="+lastValue); </script> </body> </html>
要執行上述程式,請儲存檔名為 “anyName.html(index.html)” 並右鍵單擊該檔案。在 VS Code 編輯器中選擇 “使用 Live Server 開啟” 選項。
輸出
這將產生以下輸出 −
廣告