js中用tagname和id獲取元素的3種方法

小火柴的藍色理想發表於2015-08-13
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>3種用tagname和id獲取元素的方法</title>
<style>
body{
	margin: 0;
}
ul{
	margin: 0;
	padding: 0;
	list-style: none;
}
h1{
	margin: 0;
}
</style>
</head>
<body>
<div class="box" id="box">
	<h1 class="box-tit">分類名稱</h1>
	<ul class="box-list" id="box-list">
		<li class="box-listI">
			<input class="box-listI-input">
			<button>儲存</button>
			<button>取消</button>
		</li>
		<li class="box-listI">
			<input class="box-listI-input">
			<button>儲存</button>
			<button>取消</button>
		</li>
		<li class="box-listI">
			<input class="box-listI-input">
			<button>儲存</button>
			<button>取消</button>
		</li>
	</ul>
</div>
<script>
//[1]整體法,先獲取所有的元素,再通過ai+-b的方法來算出需要的元素
var oList = document.getElementById('box-list');
var aInput = oList.getElementsByTagName('input');
var aBtn =oList.getElementsByTagName('button');

for(var i = 0; i < aBtn.length; i++){
	aBtn[i].index = i;
}
for(var i = 0; i < aInput.length; i++){
	//確定按鈕
	aBtn[2*i].onclick = function(){
		aInput[this.index/2].disabled = true;
	}
	//取消按鈕
	aBtn[2*i+1].onclick = function(){
		aInput[(this.index-1)/2].disabled = false;
		aInput[(this.index-1)/2].value = '';
		console.log(1);
	}
}
//[2]陣列法,在全域性環境下建立空陣列,遇到需要迴圈的結構時,在迴圈中獲取元素,並放入陣列
var oList = document.getElementById('box-list');
var aIn = oList.getElementsByTagName('li');
var aInput = [];
var aBtnY = [];
var aBtnX = [];
for(var i = 0; i < aIn.length; i++){
	aInput[i] = aIn[i].getElementsByTagName('input')[0];
	aBtnY[i] = aIn[i].getElementsByTagName('button')[0];
	aBtnX[i] = aIn[i].getElementsByTagName('button')[1];

	aBtnY[i].index = aBtnX[i].index = i;
	//確定按鈕
	aBtnY[i].onclick = function(){
		aInput[this.index].disabled = true;
	}
	//取消按鈕
	aBtnX[i].onclick = function(){
		aInput[this.index].disabled = false;
		aInput[this.index].value = '';
		console.log(2);
	}	
}

//[3]函式法,遇到相同的幾組元素時,只操作一組元素,並用函式傳參來實現所有的效果
var oList = document.getElementById('box-list');
var aIn = oList.getElementsByTagName('li');

function fn(i){
	var oInput  = aIn[i].getElementsByTagName('input')[0];
	var oBtnY = aIn[i].getElementsByTagName('button')[0];
	var oBtnX = aIn[i].getElementsByTagName('button')[1];
	//確定按鈕
	oBtnY.onclick = function(){
		oInput.disabled = true;
	}
	//取消按鈕
	oBtnX.onclick = function(){
		oInput.disabled = false;
		oInput.value = '';
		console.log(3);
	}		
}
for( var i = 0; i < aIn.length; i++){
	fn(i);
}
</script>	
</body>
</html>

  

相關文章