Jquery之append()和html()的區別

一、展示

1、初始頁面

在這裏插入圖片描述

2、各追加1次

在這裏插入圖片描述

3、各追加2次

在這裏插入圖片描述

4、各追加3次

在這裏插入圖片描述

二、代碼

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
    <meta charset="UTF-8">
    <title>html</title>
    <style>
        body{margin: 20px;}
        th{
            padding: 5px;
        }
        button{
            margin: 20px;
        }
        table{
            border-collapse: collapse;  /**設置小表格之間的間距爲0*/
            border-right:1px solid orange;
            border-top:1px solid orange;
        }
        table tr td,th{
            border-left:1px solid orange;
            border-bottom:1px solid orange;
        }
    </style>
    <script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
Append追加
<table class="append-add">
    <thead>
    <tr>
        <th>姓名</th>
        <th>年級</th>
        <th>年齡</th>
    </tr>
    </thead>
    <tbody>

    </tbody>
</table>

<hr/>
Html追加
<table class="html-add">
    <thead>
    <tr>
        <th>姓名</th>
        <th>年級</th>
        <th>年齡</th>
    </tr>
    </thead>
    <tbody>

    </tbody>
</table>

<button id="button1">append追加</button>
<button id="button2">html追加</button>
</body>
<script>
    //append追加按鈕
    $('#button1').click(function () {
        let html = getTableHtml();
        $('.append-add tbody').append(html);
    });

    //html追加按鈕
    $('#button2').click(function () {
        let html = getTableHtml();
        $('.html-add tbody').html(html);
    });

    /**
     * 獲取表格tr數據
     * @returns {string} 拼接的字符串
     */
    function getTableHtml() {
        return `<tr>
                    <td>姓名1</td>
                    <td>年級1</td>
                    <td><input value="1"/></td>
                </tr>
                <tr>
                    <td>姓名2</td>
                    <td>年級2</td>
                    <td><input value="2"/></td>
                </tr>
                <tr>
                    <td>姓名3</td>
                    <td>年級3</td>
                    <td><input value="3"/></td>
                </tr>`;
    }
</script>
</html>

三、總結

它們的功能缺失有點相似,但是實際上本質上是有區別:

append()函數是爲指定元素尾部附加內容,
html()函數是重置元素內部的html內容。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章