当先锋百科网

首页 1 2 3 4 5 6 7

jquery实现表单动态输入
隔行变色

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./jquery.js"></script>
</head>
  <form >
        <div>
            <label for="">姓名</label>
            <input type="text" id="user">
        </div>
        <div>
            <label for="">年龄</label>
            <input type="text" id="age">
        </div>

        <div>
            <label for="" style="visibility: hidden;">添加</label>
            <input type="button" id="btn" value="添加">
        </div>
    </form>
<div>
    <button id="openBtn">开启隔行变色</button>
    <button id="closeBtn">关闭隔行变色</button>
</div>

    <table border="1">
        <thead>
            <tr>
                <th>姓名</th>
                <th>年龄</th>
            </tr>
        </thead>
        <tbody id="tbody">
            <tr>
                <td>1</td>
                <td>2</td>
            </tr>
        </tbody>
    </table>
   <script>
        var flag="关";

        var arr=[
            {"user":"gao","age":18},
            {"user":"wgao","age":18},
            {"user":"li","age":19}
        ]

        function showTr(arr){
            var str="";
            for(var i in arr){
                var {user,age}=arr[i];
                str+=`
                <tr>
                    <td>${user}</td>
                    <td>${age}</td>
                </tr>
                `
            }
            $("#tbody").html(str);
            if(flag== "开"){
                $("#tbody >tr:even").css({
                    "background":"red"
                })
                 flag="开";
            }else{
                $("#tbody >tr:even").css({
                    "background":"white"
                })
                 flag="关"; 
            }
        }
   
        
        $(function(){
            showTr(arr);

        })

        $("#btn").click(function(){
            var user= $("#user").val();
            var age= $("#age").val();

            arr.push( { user,age } );
            showTr(arr);
        })

        $("#openBtn").click(function(){
            $("#tbody >tr:even").css({
                "background":"red"
            })
            flag="开";
        })

        $("#closeBtn").click(function(){
            $("#tbody >tr:even").css({
                "background":"white"
            })
            flag="关";
        })
        
   </script>
</body>
</html>