1. 程式人生 > >角色處理介面操作

角色處理介面操作

<!doctype html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>水果選擇</title>
	<style>
	select {
		width: 300px;
		height: 300px;
		color: block;
		background-color: lightblue;
	}
	</style>
</head>
<body>
	<!-- multiple = "multiple" 設定選項可以多選,不設定不可多選-->
	<select id="all" multiple = "multiple">
		<option >蘋果</option>
		<option >桔子</option>
		<option >橙子</option>
		<option >西瓜</option>
		<option >水蜜桃</option>
	</select>
	<input type="button" id="btn1" value=">>" />
	<input type="button" id="btn2" value="<<" />
	<input type="button" id="btn3" value=">" />
	<input type="button" id="btn4" value="<" />
	<select id="select" multiple = "multiple"></select>
	<script>
	function $el(element){
		return document.getElementById(element);
	}
	var all =$el("all");
	var select =$el("select");
	
	$el("btn1").onclick = function() {
		// for(var i = all.children.length-1; i>=0; i--) 必須這樣寫,不能從0開始迴圈加,因為appendChlid後,左邊的option的索引值會對應的改變。比如說修改後,左邊的蘋果的索引值為0 桔子索引值為1.但是進行過一次appendChild之後,桔子的索引值就變為0
		// for(var i = all.children.length-1; i>=0; i--){
		// 	var option = all.children[i];
		// 	select.appendChild(option);
		// 	// 此步驟完成後,選項的順序反了
		// }
		    var allLen = all.children.length;
			for(var i = 0;i<allLen; i++){
			console.log(i);
			var option = all.children[0];
			select.appendChild(option);
		}
	}

	$el("btn2").onclick = function() {
		var selLen = select.children.length;
		for(var i = 0;i<selLen; i++){
			console.log(i);
			var option = select.children[0];
			all.appendChild(option);
		}
	}
	$el("btn3").onclick = function() {
		var allLen = all.children.length;
		var optSel = [];
		for(var i = 0;i<allLen; i++){
			//判斷如果選項被選中個,就放到陣列中
           if(all.children[i].selected){
           		optSel.push(all.children[i]);
                //放到陣列後,將節點的狀態修改為未選中,主要是防止新增到新select中後,此項還保留迴圈中的狀態

           		all.children[i].selected = false;
           }
		}
		for(var i = 0;i<optSel.length; i++){
			console.log(i);
			var option = optSel[i];
			select.appendChild(option);
		}
	}
	$el("btn4").onclick = function() {

		var selLen = select.children.length;
		var optSel = [];
		for(var i = 0;i<selLen; i++){
           if(select.children[i].selected){
           		optSel.push(select.children[i]);
           		select.children[i].selected = false;
           }
		}
		for(var i = 0;i<optSel.length; i++){
			console.log(i);
			var option = optSel[i];
			all.appendChild(option);
		}
	}

	</script>
</body>
</html>