zoukankan      html  css  js  c++  java
  • javascript 添加元素

    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>javascript  添加元素</title>
    <script type="text/javascript" src="jquery-1.4.2.min.js"></script>
    <style type="text/css">
    
    *{ padding:0; margin:0}
    body{overflow: hidden;}
    .wrap{position: relative; 300px;height: 200px;margin: 30px auto}
    .wrap  .btn {}
    .wrap  .btn li{list-style: none;margin: 0 5px;float: left;list-style: none;}
    
    </style>
    </head>
    
    <body>
    <div class="wrap">
        <div class="btn">
            <a class="on">广州</a>
            <a>上海</a>
            <a>湛江</a>
            <a>草潭</a>
            <a>遂溪</a>
        </div>
        <ul id="con"></ul>
    </div>
    <script type="text/javascript">
        var a = document.getElementsByTagName("a");
        var ul = document.getElementById("con"); 
        var li = ul.getElementsByTagName("li");   
       
        for (var i = 0; i < a.length;i++){
           // a[i].index = i; 获取当前索引
            a[i].onclick = function(){
               if(checkTxt(this.innerHTML)){
                    var oLi = document.createElement("li");
                    oLi.innerHTML = this.innerHTML;
                    if(!li[0]){ 
                        ul.appendChild(oLi);
                    }else{
                        ul.insertBefore(oLi,li[0]);
                    }                
               }else{
                    checkTxt2(this.innerHTML);
               }
            }
        }
        function checkTxt(text){ //检测添加的元素有没有存在
            var result = true;
            for (var i = 0 ; i < li.length;i++){
                if( li[i].innerHTML == text){
                    result = false;
                }
            };
            return result;
        }
        function checkTxt2(text){ //第二次点击元素的时候。重新排序
            for (var i = 0 ; i < li.length;i++){
                if( li[i].innerHTML == text){
                    ul.insertBefore(li[i],li[0]);
                }
            };
    
        }
    </script>
    </body>
    </html>
  • 相关阅读:
    函数式宏定义与普通函数
    linux之sort用法
    HDU 4390 Number Sequence 容斥原理
    HDU 4407 Sum 容斥原理
    HDU 4059 The Boss on Mars 容斥原理
    UVA12653 Buses
    UVA 12651 Triangles
    UVA 10892
    HDU 4292 Food
    HDU 4288 Coder
  • 原文地址:https://www.cnblogs.com/enen/p/3189900.html
Copyright © 2011-2022 走看看