简体   繁体   English

如何使用.val()从表中获取最后一行数据,并使用jquery在警报中显示它?

[英]How to fetch the last row data using .val() from a table and show it in alert using jquery?

This is my script code. 这是我的脚本代码。

 $(document).ready(function() { $(".add-row").click(function() { var name = $("#name").val(); var markup = "<tr><td>" + name + "</td></tr>"; $("table tbody").append(markup); }); $(".bttn").click(function() { var i = $("#tab").find("tr").last().val(); alert(i); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form> <input type="text" id="name" placeholder="Name"> <input type="button" class="add-row" value="Add Row"> </form> <table id="tab"> <thead> <tr> <th>Name</th> </tr> </thead> <tbody> <tr> <td>Peter Parker</td> </tr> </tbody> </table> <button type="button" class="delete-row">Delete Row</button> <button type="button" class="bttn">show Row</button> 

I have a table in which it adds rows when "add row" button is clicked. 我有一个表,其中在单击“添加行”按钮时会在其中添加行。 Every time if I press "show row" button, the last row data should be shown in alert prompt. 每次按“显示行”按钮时,最后一行数据应显示在警报提示中。 How to do that using Jquery? 如何使用Jquery做到这一点?

You need to use .text() as TR element doesn't have value property. 您需要使用.text()因为TR元素没有value属性。

$("#tab").find("tr").last().text()

 $(document).ready(function() { $(".add-row").click(function() { var name = $("#name").val(); var markup = "<tr><td>" + name + "</td></tr>"; $("table tbody").append(markup); }); $(".bttn").click(function() { var i = $("#tab").find("tr").last().text().trim(); alert(i); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form> <input type="text" id="name" placeholder="Name"> <input type="button" class="add-row" value="Add Row"> </form> <table id="tab"> <thead> <tr> <th>Name</th> </tr> </thead> <tbody> <tr> <td>Peter Parker</td> </tr> </tbody> </table> <button type="button" class="delete-row">Delete Row</button> <button type="button" class="bttn">show Row</button> 

with .val() you can't achieve this because .val() works with input field, and for getting innerHTML you have to use .text() 使用.val()您无法实现此目标,因为.val()可与输入字段配合使用,而要获取innerHTML,则必须使用.text()

You can print any of row/column content using this 您可以使用此命令打印任何行/列内容

var value= $("#tab tr:eq(2) td:eq(4)").text();
alert(value)

and for last row use: 最后一行使用:

alert($('#tab tr:last').text());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM