arguments와 apply

1803 단어 html
<html>
	<head>
		
	</head>
	
	<body>
		<form name="myform">
			<div id="templete"><input type="text" value=""/></div>
			<input type="submit" value="append" id="append"/>
			<input type="button" value="calc" id="calc"/>
		</form>
		<script>
			function sum() {
				var s = 0 ;
				for(var i = 0 ; i < arguments.length ; i++) {
					s += arguments[i];
				}
				return s;
			}
			function $(id) {
				return document.getElementById(id);
			}
			document.myform.onsubmit = function() {
				var t = $('templete').cloneNode(true);
				t.id = ''
				t.firstChild.value = '';
				this.insertBefore(t , $('append'));
				var inputs = this.getElementsByTagName('INPUT');
				for(var i = 0 ; i < inputs.length ; i++) {
					if(inputs[i].type == 'text' && inputs[i].value == '') {
						inputs[i].focus();
						break;
					}
				}
				return false;
			};
			$('calc').onclick = function() {
				var arr = [];
				var inputs = document.myform.getElementsByTagName('INPUT');
				for(var i = 0 ; i < inputs.length ; i++) {
					if(inputs[i].type == 'text') {
						var num = isNaN(Number(inputs[i].value)) ? 0 : Number(inputs[i].value) ;
						arr.push(num);
					}
				}
				var s = sum.apply(null , arr);
				alert(s);
			};
		</script>
	</body>
</html>

좋은 웹페이지 즐겨찾기