JavaScript:提取行间事件、匿名函数、getelementbytagname

1.提取行间事件只能写在body中,且需要提取的标签在script代码之前,如下可运行:

原因:加载顺序,html一行一行加载顺序

改进:window.onload,见第三部分。window.onload之内的代码,将会在所有html代码加载完成后再执行,故而不会出现找不到函数或者变量的情况

<!DOCTYPE html>
<html>
<head>
	<title>example</title>
</head>
<body>
	<input id="btn1" type="button" value="变红">
<style>
	#div1{
		width: 200px;
		height: 200px;
		border: 2px solid black;
	}
</style>
<script>
	function toRed(){
		var x = document.getElementById('div1');
		x.style.backgroundColor = 'red';
	}
	function abc(){
		alert('a');
	}
	var oBtn = document.getElementById('btn1');
	oBtn.value = '变色';
	oBtn.onclick = toRed;
</script>
	<div id="div1" ></div>
</body>
</html>
<!-- 但是当将input标签移到div处,则不能运行;将script代码移到body外,则不能运行 -->

2.匿名函数

<!DOCTYPE html>
<html>
<head>
	<title>example</title>
</head>
<body>
	<input id="btn1" type="button" value="变红">
<style>
	#div1{
		width: 200px;
		height: 200px;
		border: 2px solid black;
	}
</style>
<script>
	var oBtn = document.getElementById('btn1');
	oBtn.value = '变色';
	oBtn.onclick = 	function (){
		var x = document.getElementById('div1');
		x.style.backgroundColor = 'red';
	};
</script>
	<div id="div1" ></div>
</body>
</html>

3.window.onload

<!DOCTYPE html>
<html>
<head>
	<title>example</title>
<style>
	#div1{
		width: 200px;
		height: 200px;
		border: 2px solid black;
	}
</style>
<script>
	window.onload = function (){
		var oBtn = document.getElementById('btn1');
		oBtn.value = '变色';
		oBtn.onclick = 	function (){
			var x = document.getElementById('div1');
			x.style.backgroundColor = 'red';
		};
	}
</script>
</head>
<body>
	<input id="btn1" type="button" value="变红">

	<div id="div1" ></div>
</body>
</html>

4.getelementsbytagname

var x = document.getElementsByTagName('div')

假如有5个div,则x是一个含有5个元素的数组,操作时,必须对数组中的某个元素进行操作。如:

            x[0].style.backgroundColor = 'red';
            x[1].style.backgroundColor = 'red';
            x[2].style.backgroundColor = 'red';
            x[3].style.backgroundColor = 'red';

<!DOCTYPE html>
<html>
<head>
	<title>example</title>
<style>
	#div1{
		float: left;
		margin-right: 10px;
		width: 200px;
		height: 200px;
		border: 2px solid black;
	}
</style>
<script>
	window.onload = function (){
		var oBtn = document.getElementById('btn1');
		oBtn.value = '变色';
		oBtn.onclick = 	function (){
			var x = document.getElementsByTagName('div');
			x[0].style.backgroundColor = 'red';
			x[1].style.backgroundColor = 'red';
			x[2].style.backgroundColor = 'red';
			x[3].style.backgroundColor = 'red';
		};

	}
</script>
</head>
<body>
	<input id="btn1" type="button" value="变红">

	<div id="div1" ></div>
	<div id="div1" ></div>
	<div id="div1" ></div>
	<div id="div1" ></div>
</body>
</html>

 

posted @ 2020-02-05 23:23  昨夜昙花  阅读(12)  评论(0)    收藏  举报