<!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>