1. 程式人生 > 其它 >jQuery實現隔行變色

jQuery實現隔行變色

技術標籤:jQueryjqueryjshtml

簡介:這裡我主要用到了jQuery的兩個方法odd(偶數),even(奇數)

一,html頁面

  <form>
        <div>
            <label>姓名</label>
            <input type="text" id="name">
        </div>
        <div>
            <label>年齡</label>
<input type="text" id="age"> </div> <div> <input type="button" value="新增" id="add"> </div> </form> <div> <button id="open">開啟隔行變色<
/button> <button id="even">開啟奇數隔行變色</button> <button id="close">關閉隔行變色</button> </div> <table border="1" cellspacing="0" cellpadding="0"> <tr> <thead> <
th>姓名</th> <th>年齡</th> </thead> </tr> <tbody id="tbody"> </tbody> </table>

二,js程式碼

 <script>
        var arr = [{ "name": "qian", "age": 19 }, { "name": "li", "age": 19 }];
        
        var flag = "關";/*  偶數的變數    */
        var flag2 = "關";/*  奇數的變數    */
        /*  新增資料列表點選事件    */
        $("#add").click(function () {
            var name = $("#name").val();
            var age = $("#age").val();
            arr.push({ name, age });
            showTab(arr);
        })
        /*  預設載入渲染    */
        $(function () {
            showTab(arr);
        })
        /*  渲染方法    */
        function showTab(arr) {
            var str = "";
            $.each(arr, function (i, v) {
                str += `
            <tr>
                <td>${v.name}</td>
                <td>${v.age}</td>
            </tr>
              `
            })
            $("#tbody").html(str);
            /*  頁面渲染對每個點選事件的變數賦值    */
            if (flag == "關") {
                $("#tbody>tr:odd").css({ "background": "white" });
                flag = "關";
            } else {
                $("#tbody>tr:odd").css({ "background": "red" });
                flag = "開";
            }
            if (flag2 == "關") { 
                $("#tbody>tr:even").css({ "background": "white" });
                flag2 = "關";
            } else {
                $("#tbody>tr:even").css({ "background": "red" });
                flag2 = "開";
            }
        }
        /*  實現偶數行的點選事件    */
        $("#open").click(function () {
            $("#tbody>tr:odd").css({ "background": "red" });
            $("#tbody>tr:even").css({ "background": "white" });
            flag = "開";
            flag2 = "關";
        })
        /*  實現奇數行的點選事件    */
        $("#even").click(function () {
            $("#tbody>tr:even").css({ "background": "red" });
            $("#tbody>tr:odd").css({ "background": "white" });
            flag = "關";
            flag2 = "開";
        })

        /*  關閉隔行變色的點選事件    */
        $("#close").click(function () {
            $("#tbody>tr").css({ "background": "white" });
            flag = "關";
            flag2 = "關";
        })
    </script>

路過的鐵子們給我點個贊在這裡插入圖片描述