邏輯思考之選擇限定範圍內的數量插入不指定位置並且具有替換功能

這個邏輯文字描述好像很複雜,具體到實踐功能就知道我想表達的是什麼了。把邏輯想通了,這個功能也就寫出來了,demo如下:

請轉載此文的朋友務必附帶原文鏈接,謝謝。

原文鏈接:http://xuyran.blog.51cto.com/11641754/1890678

wKiom1h0XRLRJocNAAAPdYlAC5I332.png-wh_50

<!DOCTYPE html PUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <!--引用jquery-->
    <script src="http://code.jquery.com/jquery-2.0.3.min.js" type="text/javascript"></script>
    <style type="text/css">
    *{
    	margin: 0px;
    	padding: 0px;
    	list-style: none;
    }
    .list{
    	padding: 10px;
    	border: solid 1px #000000;
    	width: 500px;
    	height: 200px;
    	margin-top: 20px;
    }
    .list li{
    	float: left;
    	width: 100px;
    	border-bottom: dashed 1px #C4C4C4;
    	padding-bottom: 5px;
    	margin-top: 20px;
    	margin-left: 20px;
    }
    .check{
    	float: left;
    	width: 8px;
    	height: 8px;
    	background: #FFFFFF;
    	border: solid 1px #000000;
    	border-radius: 50%;
		margin-top: 5px;
		margin-right: 10px;
    }
    .check.active{
    	background: #000000;
    }
    .bottom li{
    	
    }
    </style>
    <script type="text/javascript">
    	$(function(){
    		var arr = []; //保存已經選中的項插入的對應的位置
    		$(".check").on("click",function(){
    			$(this).addClass("active");
    			var len = $(".top").find(".active").length; //已經選中的數量
    			var txt = $(this).parent().text(); //要插入的內容
    			if($(this).hasClass("active") && ifExist()&& len <= 4){  //狀態:如果已經選中而且之前沒有插入過同時總數量小於限定數量,則執行如下
	    			$(".bottom li").each(function(){
	    				var con = $(this).text();
    					if(!con){
    					arr[txt] = $(this).index(); 
    					$(this).html(txt);
    					return false;
    					}	
	    			});
    			}else if($(this).hasClass("active") && !ifExist()){  //狀態:如果已經選中,之前已經插入過, 則執行如下
    				$(this).removeClass("active");
    				var index = arr[txt];  //讀取當前選中之前插入的位置
    				$(".bottom li").eq(index).html("");
    			}else{
    				$(this).removeClass("active");
    				alert("最多隻能選擇4個");
    			}
    			function ifExist(){
    				var result;
					$(".bottom li").each(function(){ //遍歷插入列表中要插入選項是否存在,如果存在返回false,否則返回true
	    				var con = $(this).text();
						if(con != txt){
							result = true;
						}else{
							result = false;
							return false;
						}
	    			});
	    			return result;
    			}
    		});
    	
    	})
    </script>
</head>
<body>
<ul class="list top">
	<li><span class="check"></span>11111</li>
	<li><span class="check"></span>22222</li>
	<li><span class="check"></span>33333</li>
	<li><span class="check"></span>44444</li>
	<li><span class="check"></span>55555</li>
	<li><span class="check"></span>66666</li>
</ul>
<ul class="list bottom">
	<li></li>
	<li></li>
	<li></li>
	<li></li>
</ul>
<script>
	
</script>
</body>
    
</html>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章