聲明:例子的chosen是jquery的select下拉插件,須要自行去下載;狠狠戳這裏:https://harvesthq.github.io/chosen/javascript
<script src="vendors/bower_components/jquery/dist/jquery.min.js"></script> <script type="text/javascript"> $(function(){ var trouble_selected_data = new Object(); $("#trouble_selected").change(function(){ var this_id = $(this).find('option:selected').attr('data-id') //選定的option var this_val =$(this).val(); if (this_id == undefined) { alert("請選擇") return false; } if (this_id in trouble_selected_data == true ) { alert("添加已存在!") return false; } else { //寫入對象----獲取id和文本值 trouble_selected_data[this_id] = { text: $(this).val()} console.log(trouble_selected_data); //遍歷對象 寫入數組 var inner = new Array(); for (var x in trouble_selected_data) { //for in 中的X是遍歷的是鍵 inner.push('<li data-id="' + x + '"><div>' + trouble_selected_data[x].text + '</div> <i class="zmdi zmdi-close"></i></li>'); } console.log(inner) //寫入 $('#result_select').html(inner.join('')); //數組合並 //刪除 $("#result_select li").click(function(){ var li_id = $(this).attr("data-id"); alert(li_id) delete trouble_selected_data[li_id]; $(this).remove(); console.log(trouble_selected_data); //返回最新刪除後的結果; }) } }) }) </script>
這裏注意,爲了後續保證排除數據的惟一性,我給每一個option給了給data-id。在js中,我是這樣判斷的:if (this_id in trouble_selected_data == true ),【對象基礎知識:判斷對象是否含有某屬性,in 操做符,返回 true 或 false。】css
<div class="row"> <div class="col-sm-6" > <div class="form-group"> <div class="fg-line"> <select class="chosen" id="trouble_selected"> <option>請選擇故障描述</option> <option data-id="fdjyx">發動機異響故障</option> <option data-id="fdjzs">發動機轉速太高故障</option> <option data-id="bsxgd">變速箱掛擋故障</option> <option data-id="scpyx">剎車片異響故障</option> </select> </div> </div> </div> <div class="col-sm-6 p-t-5" > <ul id="result_select"></ul> </div> </div>
#result_select li{ position:relative; cursor: pointer; float:left; margin-left: 20px; margin-bottom: 20px; padding: 0px 7px 0px 15px; width:150px; border: 1px solid #ccc;} #result_select li:hover{background: #d0f0f8; border: 1px solid #7fd9ef;} #result_select li > div{ width: 105px; height: 32px; line-height: 32px; overflow: hidden; white-space:nowrap; text-overflow:ellipsis; } #result_select li i{ position: absolute; top: 10px; right: 3px; width: 20px; height: 20px; }
篇外話:html
每次的博客,後續讀,都會以爲有能夠再優化的部分,此例也不例外,在去重後,寫入對象,java
這裏是① 遍歷對象 ② 添加到數組 ③ 而後經過html()寫到結果區中。這裏太過複雜~~~~~jquery
for (var y in obj) { $('#reasult-list ul').append('<li data-id="' + y + '">' + obj[y] + '</li>') }
簡單的版本,詳見 jquery-動態獲取-存到數組-存到對象,稍後幾天更新。。。。。git