Home > Web Front-end > JS Tutorial > body text

jQuery Tips: Dynamically insert new rows into a table

PHPz
Release: 2024-02-28 11:51:03
Original
746 people have browsed it

jQuery Tips: Dynamically insert new rows into a table

Title: jQuery Tips: Dynamically Insert New Rows into Tables

In web development, it is often necessary to dynamically insert new rows into tables. This function It's very easy to achieve using jQuery. The following will introduce how to use jQuery to dynamically insert new rows into the table, and provide specific code examples.

First, make sure the jQuery library is introduced in the HTML file, either through a CDN link or a local file. The following is a simple HTML structure, containing a table and a button:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>动态在表格中插入新的行</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<table id="myTable">
<tr>
<th>Name</th>
<th>Age</th>
</tr>
</table>
<button id="addRowBtn">新增行</button>
</body>
</html>
Copy after login

Next, we need to write jQuery code to insert a new row in the table when the button is clicked. The code is as follows:

$(document).ready(function() {
  $('#addRowBtn').click(function() {
    var name = prompt('请输入姓名:');
    var age = prompt('请输入年龄:');
    var newRow = '<tr><td>' + name + '</td><td>' + age + '</td></tr>';
    $('#myTable').append(newRow);
  });
});
Copy after login

In the above code, we first bind the click event of the button after the document is loaded. When the button is clicked, two prompt boxes pop up to enter your name and age respectively, and HTML code that concatenates the entered values ​​into a new table row. Finally, use jQuery's append() method to insert the new row into the table.

Now, we have completed the function of dynamically inserting new rows in the table. You can copy and paste the above HTML and jQuery code into an HTML file, open it in the browser, and click the button to test the effect. Through this example, I hope it can help you learn how to use jQuery to dynamically insert new rows into a table.

The above is the detailed content of jQuery Tips: Dynamically insert new rows into a table. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template