Home Web Front-end Front-end Q&A jquery does addition, deletion, modification and query

jquery does addition, deletion, modification and query

May 08, 2023 pm 08:53 PM

With the popularization of Web applications, the demand for more timely response from the client is getting higher and higher. Simple page interaction can no longer meet the needs of the public. At this time, the JavaScript library jQuery came into being. In most cases, if you need to perform operations such as adding, deleting, modifying, and querying data on the page, jQuery is a very convenient choice. Next we will discuss how to use jQuery to implement the add, delete, modify and check functions.

1. Page preparation

On the HTML page, you need to prepare the elements required for addition, deletion, modification and query, as shown below:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

<!DOCTYPE html>

<html>

<head>

    <title>jQuery增删改查</title>

    <meta charset="UTF-8">

    <link rel="stylesheet" type="text/css" href="./css/styles.css">

    <script src="https://cdn.bootcss.com/jquery/3.5.1/jquery.min.js"></script>

    <script src="./js/jquery_method.js"></script>

</head>

<body>

 

    <h1>jQuery增删改查</h1>

 

    <form id="add_form">

        <label for="add_name">名称:</label>

        <input type="text" id="add_name" name="name" required><br>

        <label for="add_age">年龄:</label>

        <input type="number" id="add_age" name="age" required><br>

        <button type="submit" id="add_btn">添加</button>

    </form>

 

    <table id="table" border="1">

        <tr>

            <th>ID</th>

            <th>名称</th>

            <th>年龄</th>

            <th>操作</th>

        </tr>

    </table>

 

</body>

</html>

Copy after login

Which includes the form elements and data tables, as well as jQuery references and custom JavaScript files.

2. Add data

When using jQuery to add data, you need to define a form in the HTML page and add a submit button. And write an event listener in JavaScript (usually jQuery_method.js) to get the form's data and add it to the table. The code is as follows:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

$(document).ready(function () {

    // 监听添加操作

    $('#add_btn').on('click', function (e) {

        e.preventDefault();     // 阻止表单默认提交行为

        const name = $('#add_name').val();

        const age = $('#add_age').val();

        addData(name, age);

    });

});

 

function addData(name, age) {

    // 构造表格行

    const tr = $('<tr>');

    tr.append(`<td id="id_${name}"></td>`)

        .append(`<td>${name}</td>`)

        .append(`<td>${age}</td>`);

    // 构造表格行中的操作列

    const td = $('<td>');

    const btn_update = $('<button>修改</button>');

    const btn_delete = $('<button>删除</button>');

    btn_update.on('click', function () {

        updateData(name);

    });

    btn_delete.on('click', function () {

        deleteData(name);

    });

    td.append(btn_update).append(btn_delete);

    tr.append(td);

    // 添加到表格中

    $('#table').append(tr);

 

    // 分配ID

    const id = $('#table tr').length;

    $(`#id_${name}`).html(id);

}

Copy after login

In the above code, we use jQuery to listen to the submit button of the form, obtain the data entered in the form, and add two elements to the last td button elements, one for modifying data and one for deleting data. Function addData() is used to add data to the table and assign an ID to each row of data.

3. Query data

Querying data can be achieved by directly operating table elements. Take querying a name as an example:

1

2

3

4

function queryData(name) {

    const tr = $(`#table tr td:nth-child(2):contains(${name})`).parent();

    return tr;

}

Copy after login

In the above code, we use jQuery's selector syntax to select all rows of data that contain the specified name, and pass the .parent() method Returns the tr element it is located in.

4. Modify data

To modify data, you first need to query the data that needs to be modified, and then display it on a modal box (usually a form), waiting for the user to input the data that needs to be modified. value and submit the modified data. After adding an event listener for closing the modal, the data is updated in the table based on the value entered by the user. The code is as follows:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

function updateData(name) {

    const tr = queryData(name);

    const old_name = tr.find('td').eq(1).text();

    const old_age = tr.find('td').eq(2).text();

    const $form_update = $(`

            <form>

                <label for="update_name">名称:</label>

                <input type="text" id="update_name" name="update_name" value="${old_name}" required><br>

                <label for="update_age">年龄:</label>

                <input type="number" id="update_age" name="update_age" value="${old_age}" required><br>

                <button type="submit">修改</button>

                <button type="button" id="close_btn">关闭</button>

            </form>

        `);

    $('#table').after($form_update);

 

    $form_update.on('submit', function (e) {

        e.preventDefault();

        const new_name = $('#update_name').val();

        const new_age = $('#update_age').val();

        tr.find('td').eq(1).text(new_name);

        tr.find('td').eq(2).text(new_age);

        tr.attr('id', `id_${new_name}`);

        $form_update.remove();

    });

    $('#close_btn').on('click', function () {

        $form_update.remove();

    });

}

Copy after login

In the above code, we use jQuery selector syntax to select the data that needs to be modified and assign it an ID. Then, the data that needs to be modified is displayed to the user by popping up a modal box, allowing the user to make modifications. After the modification is completed, use jQuery to find the row again and update the data in the table. The operation of closing the button is also achieved by closing the modal box.

5. Delete data

For deleting data, you still need to display the data that needs to be deleted to the user through a modal box, and then listen to the click event on the delete button and add it to the table Delete this line. The code is as follows:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

function deleteData(name) {

    const tr = queryData(name);

    const $form_delete = $(`

            <form>

                <label>

                    您确定要删除名称为 <strong>${name}</strong> 的数据吗?

                </label>

                <button type="submit">确定</button>

                <button type="button" id="close_btn">取消</button>

            </form>

        `);

    $('#table').after($form_delete);

 

    $form_delete.on('submit', function (e) {

        e.preventDefault();

        tr.remove();

        $form_delete.remove();

    });

    $('#close_btn').on('click', function () {

        $form_delete.remove();

    });

}

Copy after login

In the above code, we use jQuery's selector syntax to select the data that needs to be deleted, and display the data that needs to be deleted to the user by popping up a modal box. After the user clicks OK, the row of data is deleted from the table. For the operation of the cancel button, the modal box is still closed.

6. Summary

Through the above code, we can find that it is very easy to use jQuery to add, delete, modify and check. After the page preparation is completed, use jQuery's selector syntax to select the DOM element that needs to be operated, and use jQuery's event listener to handle the corresponding event. At the same time, jQuery's concise code also brings great convenience. Using jQuery is a very good choice for add, delete, modify and query functions that do not require complex logic.

The above is the detailed content of jquery does addition, deletion, modification and query. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

React's Role in HTML: Enhancing User Experience React's Role in HTML: Enhancing User Experience Apr 09, 2025 am 12:11 AM

React combines JSX and HTML to improve user experience. 1) JSX embeds HTML to make development more intuitive. 2) The virtual DOM mechanism optimizes performance and reduces DOM operations. 3) Component-based management UI to improve maintainability. 4) State management and event processing enhance interactivity.

What are the limitations of Vue 2's reactivity system with regard to array and object changes? What are the limitations of Vue 2's reactivity system with regard to array and object changes? Mar 25, 2025 pm 02:07 PM

Vue 2's reactivity system struggles with direct array index setting, length modification, and object property addition/deletion. Developers can use Vue's mutation methods and Vue.set() to ensure reactivity.

React Components: Creating Reusable Elements in HTML React Components: Creating Reusable Elements in HTML Apr 08, 2025 pm 05:53 PM

React components can be defined by functions or classes, encapsulating UI logic and accepting input data through props. 1) Define components: Use functions or classes to return React elements. 2) Rendering component: React calls render method or executes function component. 3) Multiplexing components: pass data through props to build a complex UI. The lifecycle approach of components allows logic to be executed at different stages, improving development efficiency and code maintainability.

React and the Frontend: Building Interactive Experiences React and the Frontend: Building Interactive Experiences Apr 11, 2025 am 12:02 AM

React is the preferred tool for building interactive front-end experiences. 1) React simplifies UI development through componentization and virtual DOM. 2) Components are divided into function components and class components. Function components are simpler and class components provide more life cycle methods. 3) The working principle of React relies on virtual DOM and reconciliation algorithm to improve performance. 4) State management uses useState or this.state, and life cycle methods such as componentDidMount are used for specific logic. 5) Basic usage includes creating components and managing state, and advanced usage involves custom hooks and performance optimization. 6) Common errors include improper status updates and performance issues, debugging skills include using ReactDevTools and Excellent

What are the benefits of using TypeScript with React? What are the benefits of using TypeScript with React? Mar 27, 2025 pm 05:43 PM

TypeScript enhances React development by providing type safety, improving code quality, and offering better IDE support, thus reducing errors and improving maintainability.

How can you use useReducer for complex state management? How can you use useReducer for complex state management? Mar 26, 2025 pm 06:29 PM

The article explains using useReducer for complex state management in React, detailing its benefits over useState and how to integrate it with useEffect for side effects.

What are functional components in Vue.js? When are they useful? What are functional components in Vue.js? When are they useful? Mar 25, 2025 pm 01:54 PM

Functional components in Vue.js are stateless, lightweight, and lack lifecycle hooks, ideal for rendering pure data and optimizing performance. They differ from stateful components by not having state or reactivity, using render functions directly, a

How do you ensure that your React components are accessible? What tools can you use? How do you ensure that your React components are accessible? What tools can you use? Mar 27, 2025 pm 05:41 PM

The article discusses strategies and tools for ensuring React components are accessible, focusing on semantic HTML, ARIA attributes, keyboard navigation, and color contrast. It recommends using tools like eslint-plugin-jsx-a11y and axe-core for testi

See all articles