美文网首页
jquery动态添加,删除,上下移动元素代码!

jquery动态添加,删除,上下移动元素代码!

作者: DragonersLi | 来源:发表于2017-07-27 15:53 被阅读51次

    效果图:

    图片.png

    代码:

    <!doctype html>  
    <html>  
    <head>  
    <meta charset="utf-8">  
    <title>Jquery动态添加及删除页面节点</title>  
    <script src="http://code.jquery.com/jquery-1.8.3.min.js"></script><!--引用jqurey库文件-->  
    <style>  
        .container{ width:1000px; margin:0 auto;}   
        .add{ line-height:30px;}  
        li{ list-style:none;}  
        span{cursor:pointer;}  
    </style>  
     
     
    <script>  
        $(function(){//页面加载完毕后执行  
        $("#add").click(function(){//添加操作  
               
                $("#li").before('<li><input type="text" name="text[]" ><span><a href="#" >删除</a></span>  <a href="#" onclick="up(this)">上移</a>  <a href="#" onclick="down(this)">下移</a></li>');//在p标签前加入所要生成的代码  
            });  
        });  
        $("span").live("click",function(){//通过 live() 方法附加的事件处理程序适用于匹配选择器的当前及未来的元素(比如由脚本创建的新元素)  
                $(this).parent().remove();//移除当前点击元素的父元素  
            });  
            
    //上移        
    function up(obj) {
        var current_li = $(obj).parents("li"); 
        var prev_li = current_li.prev();
        if (prev_li.length > 0) {
            prev_li.insertAfter(current_li);
        }else{//prev_li.length == 0
            alert("已经移到顶层了!");
            return;
        } 
    }
    //下移
    function down(obj) {
        var current_li = $(obj).parents("li");
        var next_li = current_li.next();
        if (next_li.length > 0) {
        next_li.insertBefore(current_li);
        }else{//next_li.length == 0
            alert("已经移到底层了!");
            return;
          }
    }
    </script>  
    </head>  
       <body>   
       
        <input value="添 加" type="button" id="add"/>  
        
        <ul class="add"><li id="li"></li></ul>  
       
       </body>
    </html>
      
    
    
    

    相关文章

      网友评论

          本文标题:jquery动态添加,删除,上下移动元素代码!

          本文链接:https://www.haomeiwen.com/subject/akpwgttx.html