jquery动态添加元素和删除

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
    <script type="text/javascript">
        Array.prototype.in_array = function(val){
            for(var i=0;i<this.length;i++){
                if(val == this[i]){
                    return true;
                }
            }
            return false;
        }

        String.prototype.trim = function() {
            return this.replace(/^\s+|\s+$/g, '');
        }

        $(function(){
            $(".btn_small").live("click",function(){
                var val = $("#wd_white_ip_list").val().trim();

                if(val == ""){
                    return;
                }

                var arr = [];
                $(".col1").each(function(){
                    arr.push($(this).html());
                });
                if(arr.in_array(val)){
                    alert("已存在");
                    return;
                }

                var tr = $("<tr>");
                var td1 = $("<td>").html(val).addClass("col1");
                tr.append(td1);
                var td2 = $("<td>").html('<input type="button" class="del_ip" value="删除"/>').addClass("col2");
                tr.append(td2);
                $("#white_list2").append(tr);
            });

            $(".del_ip").live("click",function(){
                var tr = $(this).parent().parent();
                tr.remove();
            });
        });
    </script>
</head>
<body>
    <input id="wd_white_ip_list" name="wd_white_ip_list" type="text" value="" class="input_20_table"/>
    <input type="button" class="btn_small" value="添加"/>
    <div id="user-grid2" >
        <table width="100%" border="0" cellspacing="0" cellpadding="0" id="white_list2">
            <tr>
                <td class="col1">dfdfdfdfdfdfdffdfdf.com</td>
                <td class="col2"><input type="button" class="del_ip" value="删除"/></td>
            </tr>
            <tr>
                <td class="col1">sdsdsdsdsd</td>
                <td class="col2"><input type="button" class="del_ip" value="删除"/></td>
            </tr>
        </table>
    </div>

</body>
</html>

 

posted @ 2014-07-30 14:15  wh-王东  阅读(584)  评论(0)    收藏  举报