Blogger Information
Blog 11
fans 0
comment 0
visits 21123
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
根据id获取元素
玄夜的博客
Original
2927 people have browsed it
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<!--document是document对象的一个引用,是一个全局变量-->
		<ul>
			<li id="item1">item01</li>
			<li>item02</li>
			<li id="item3">item03</li>
			<li>item04</li>
			<li id="item5">item05</li>
		</ul>
	</body>
	<script type="text/javascript" src="../js/jquery-1.11.1.min.js" ></script>
	<script>
		
		function getelement(){
		var item = document.getElementsByTagName('li')
		for (i=0;i<item.length;i++) {
			var itemId = item[i].id
			if(itemId !=""){
				document.getElementById(itemId).style.background = 'pink'
			}
		}
		}
		getelement()
		
		function getelements(){    //参数是多个id字符串
			var elements = {};     //保存获取到的dom对象元素
			for (var i=0;i<arguments.length;i++) {
				var id = arguments[i];    //获取参数id
				var elt = document.getElementById(id);    //根据id字符串
				if(elt === null){
					throw new Error("没有这个元素"+id);      //抛出异常
				}
				elements[id] = elt;        //获取到的元素保存到结果集合中
			}
			return elements;         //将获取到的元素返回
		}
		
		//根据id获取页面上的指定元素,返回一个关联数组对象,键名就是id
		var elements = getelements('item1','item3','item5');
//		console.log(elements);
		for (var Key in elements) {
			elements[Key].style.background = 'yellow'
		}
		getelements()
		
	</script>
</html>


Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post