for문 사용

function getRandomArray(idxSize, range) {
	/* 랜덤 수를 가진 배열을 반환하는 메서드.
	 * idxSize : 반환받을 배열 사이즈, 
	 * range : 랜덤 수의 범위
	 */
	var indexs = new Array(); // 랜덤 인덱스 배열
	var hasValue = false; //같은 값이 있는지 확인하기 위한 변수
	
	if(idxSize > range) {
		console.error('index size > range');
		return indexs;
	}
	
	while(indexs.length < idxSize) {
		hasValue = false;
		var temp = parseInt(Math.random() * range);
		for(c = 0; c < indexs.length; c++) {
			if(temp == indexs[c]) {
				hasValue = true;
				break;
			}
		}
		if(hasValue == false) {
			indexs.push(temp);
		} 
	}
	return indexs;
}

// 사용방법
var indexs = new Array();
indexs = console.log(getRandomArray(5, 10));
indexs.forEach(function(value) {
	console.log(value);
});


Set 사용

set으로 좀 더 짧은 코드를 작성할 수 있지만 크롬과 오페라, 파이어폭스에서만 지원되며 익스플로러에서는 Set을 지원하지 않는다.

var indexs = new Set();
while(1) {
	indexs.add(parseInt(Math.random() * 10));
	if(indexs.size == 5) {
		console.log(indexs.size);
		break;
	}
}

indexs.forEach(function(value) {
	console.log(value);
});

main page

Javascript를 이용해서 다음 페이지에 파라미터 넘기기 위한 방법이다.

<html>
 <head>
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
  <script>
   function setChildValue(index) {
    window.location.href = "subPage.html?index=" + index;
   }
  </script>
 </head>
 <body>
  <button onclick="setChildValue(123)">Click me</button>
 </body>
</html>

sub page

방법 1

<!DOCTYPE html>
<html>
<head>
	<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
	<script type="text/javascript">
		$(document).ready(function () {
			var val = location.href.substr(
				location.href.lastIndexOf('=') + 1
			);
			console.log('val : ' + val);
		});
	</script>
</head>
<body>

</body>
</html>

방법 2

<!DOCTYPE html>
<html>
<head>
	<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
	<script type="text/javascript">
		function getURLParameter(name) {
			return decodeURI(
			 (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
			);
		}

		function getURLParameter2(name) {
			 return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null
		}
		$(document).ready(function () {
			console.log('val : ' + getURLParameter('index'));
			console.log('val : ' + getURLParameter2('index'));
		}
	</script>
</head>
<body>
</body>
</html>

방법 3

<!DOCTYPE html>
<html>
<head>
	<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
	<script type="text/javascript">
		var getParameter = function (param) {
			var returnValue;
			var url = location.href;
			var parameters = (url.slice(url.indexOf('?') + 1, url.length)).split('&');
			for (var i = 0; i < parameters.length; i++) {
				var varName = parameters[i].split('=')[0];
				if (varName.toUpperCase() == param.toUpperCase()) {
					returnValue = parameters[i].split('=')[1];
					return decodeURIComponent(returnValue);
				}
			}
		};
		$(document).ready(function () {
			console.log('val : ' + getParameter('index'));
		}
	</script>
</head>
<body>
</body>
</html>

메인화면에서 로그인버튼을 image로 두었을 경우, image는 submit을 가지고 있다.

<input type="image" src="../login.png" onClick="login(e);">
// type="submit"과 같다.

이 경우 login() 함수에서 submit을 줄 경우 중복된 결과가 나온다. 

return false; 를 사용하거나 img태그로 사용하는 방법으로 아래와 같다.

<!--  <input type="image"> submit 막는 방법  -->

<input type="image" src="../login.png" onClick="login(e); return false;">
// return false; 를 넣는 방법.

<img src="../login.png" onClick="login(e);">
// 버튼을 이미지태그로 사용하는 방법.


텍스트박스에 기본값 문자열이 나타나고 클릭시에 사라지는 스크립트코드

function checkValue(element) {
	if(element.value =="")
		alert("비밀번호를 입력하세요");
}

function clearText(txt) {
	if (txt.defaultValue==txt.value)
		txt.value = "";
}

사용방법

onFocus="clearText(form.id)" onBlur="checkValue(form.pw)"


먼저 사용자의 웹 브라우저를 확인할 수 있는 코드이다.

 navigator.userAgent


위 코드를 이용해서 브라우저를 확인하고 각 브라우저 별로 처리할 수 있는 코드이다.

var Browser = {
	chk : navigator.userAgent.toLowerCase()
}
 
Browser = {
	ie : Browser.chk.indexOf('msie') != -1,
	ie6 : Browser.chk.indexOf('msie 6') != -1,
	ie7 : Browser.chk.indexOf('msie 7') != -1,
	ie8 : Browser.chk.indexOf('msie 8') != -1,
	ie9 : Browser.chk.indexOf('msie 9') != -1,
	ie10 : Browser.chk.indexOf('msie 10') != -1,
	opera : !!window.opera,
	safari : Browser.chk.indexOf('safari') != -1,
	safari3 : Browser.chk.indexOf('applewebkir/5') != -1,
	mac : Browser.chk.indexOf('mac') != -1,
	chrome : Browser.chk.indexOf('chrome') != -1,
	firefox : Browser.chk.indexOf('firefox') != -1
}
 
if ((Browser.ie9) || (Browser.ie10)) {
	// 브라우저가 IE9, 10일 때 실행할 코드
} else if(Browser.chrome) {
	// chrome
} else if(Browser.firefox) {
	// fierfox
} else {
	// 그 외 실행할 코드
}


 읽기 좋은 자바스크립트 코딩 기법에선 브라우저 탐지를 매우 안좋은 습관이고 반드시 피해야 한다고 한다.

 "기능 추론과 브라우저 탐지는 매우 안 좋은 습관이고 반드시 피해야 합니다. 어떤 상황이든 기능 탐지를 사용하는 것이 가장 좋습니다. … 브라우저 추론은 유지보수에 좋지도 않고 브라우저가 새로 배포될 때마다 업데이트해야 하므로 코드에서 벗어날 수 없게 될지도 모릅니다."


리터럴(literal)이란?

프로그램에 직접 나타나는 데이터 값.


23		// 숫자 23
2.3		// 실수형 2.3
"hello world"	// 문자열
'opid'		// 문자열
true		// boolean 값
false		// boolean 값
/javascript/gi	// 정규표현식 리터럴
null		// 존재하지 않는 값



읽기 좋은 자바스크립트 코딩 기법에서는 기본 리터럴에 대해서 다음과 같이 권장한다.

"문자열은 반드시 작은따옴표가 아닌 큰따옴표를 사용하고 한 줄로 작성합니다. … "


" null 값은 반드시 다음 상황에서만 사용합니다.

  • 객체 값을 나중에 할당할 변수를 초기화할 때
  • 초기화된 변수에 객체 값이 할당되었는지 비교할 때
  • 객체를 인자로 넘겨야 하는 함수를 호출할 때
  • 함수에서 객체를 반환해야 할 때


아래와 같은 함수를 정의한다.

function checkLen(pwd) {
	len = pwd.value.length
	if(len < 4 || len > 8) {
		alert("비밀번호는 4자 이상 8자 이하로 입력하세요.")
		return false;
	}
	else
		return ture;
}


사용방법은 아래와 같다.

onclick="chexkLen(form1.pwd)"


<script language="JavaScript">
var now = new Date();
var then = new Date("august 5,2012");
var gap = now.getTime() - then.getTime();
gap = Math.floor(gap / (1000 * 60 * 60 * 24));
document.write(gap);
</script>


위 코드를 이용해 티스토리 사이드바에 모듈로 추가해 사용할 수도 있다.

alert(); // 경고창등 메세지를 나타낼수 있는 대화 상자

<script language="javascript">
alert("내용");
</script>


confirm(); // 사용자의 확인을 받기 위한 대화 상자

<script language="javascript">
var confirmVal = confirm("내용");
document.write(confirmVal);
</script>


prompt(); // 사용자로부터 내용을 입력받을 수 있는 대화상자

<script language="javascript">
var promptVal = prompt("내용");
document.write(promptVal);
</script>



미리 정의되어 있는 isNaN()를 이용한다.


사진 참조


function isOnlyNum(txt) {
	uPhone = txt.value;
	if(isNaN(uPhone)) {
		alert("'전화번호'" 필드에는 숫자만 입력해 주세요");
		txt.value = "";
		txt.focus();
	}
	else alert("등록되었습니다.");
}


적용 방법은 아래와 같이 적용한다.


onclick="isOnlyNum(myform.phone)"


아래 코드는 doFunction() 메서드를 이벤트핸들러에 추가하는 코드이다.

// 변수.addEventListener("click", 메서드, false); 
var evt = document.getElementById("event_btn");
evt.addEventListener("click", doFunction, false);


문제점 : IE8 이하 버전에서는 addEventListener()를 지원하지 않는다.

해결방안 : 

function addListener(target, type, handler) {
	if (target.addEventListener) {
		target.addEventListener(type, handler, false);
	} else if (target.attachEvent) {
		target.attachEvent("on" + type, handler);    
	} else {
		target["on" + type] = handler;
	}
}

DOM 레벨 0에 따르는 브라우저에서도 on 프로퍼티를 이용해 이벤트 헨들러를 추가할 수 있다.

이전 포스팅한 로딩바 구현은 어떤 클릭 이벤트가 일어났을 때, 넘어가기전까지 레이어를 보여주는 방식이었더라면

이번 로딩바는 페이지를 로드하는 처음 시점에서 레이어를 보여주고 리소스가 모두 로드되었을 때 레이어를 가려주는 방법이다. 이전 포스팅 내용은 맨 아래 링크로 남겨두었다.


실행되는 페이지에 아래 코드를 넣어준다.

<script type="text/javascript" src="../includes/jquery.js"/>
<script type="text/javascript">
    (function() { loading_ta(1); })();
    $(window).load(function(){ loading_ta(0); });
</script>


아래 코드는 각 페이지에 넣어도되고 js파일로 만들어 포함시켜도 된다.

function loading_ta(view) {
    if(view) {
        var loading_left = '50%', loading_top = '50%'; // 적용이 안되는 상황을 고려해 기본 값 설정 
        if (typeof (window.innerWidth) == 'number') { //Chrome
            loading_left = window.innerWidth / 2;
            loading_top = window.innerHeight / 2;
        } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
            loading_left = document.documentElement.clientWidth / 2;
            loading_top = document.documentElement.clientHeight / 2;
        } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) { //IE9
            loading_left = document.body.clientWidth / 2;
            loading_top = document.body.clientHeight / 2;
        }
        var lo_div = "<div name='lo_div' id='lo_div' style='position:absolute; height:100%; width:100%; top:0; left:0; background:#000000; opacity:0.0; filter:alpha(opacity=00); z-index:9995;'></div><div name='lo_div' id='lo_div' style='position:absolute; height:70; width:200; top:"+loading_top+"; left:"+loading_left+"; margin-left:-100px; margin-top:-35px;  background:#ffffff; opacity:0.8; filter:alpha(opacity=80); z-index:9996;'></div><div name='lo_div' id='lo_div' style='position:absolute; height:70; width:200; top:"+loading_top+"; left:"+loading_left+"; margin-left:-100px; margin-top:-35px; text-align:center; z-index:9998;'><p style='height:30; width:200; margin:15px 0px 15px 0px; font-weight:bold;'>데이터 처리 중입니다.<br>잠시 기다려주십시오.</p></div>";
        document.write(lo_div);
    } else if(!view) {
        var lo_ta = document.getElementsByName("lo_div");
        lo_ta[0].style.display="none";
        lo_ta[1].style.display="none";
        lo_ta[2].style.display="none";
    }
}

 2013/08/02 - [대학 정리노트/JavaScript] - [Javascript] 로딩중 레이어 만들고 띄우기



문제점 : 여러개의 Element를 다룰 때 getElementsByName을 사용한다. 하지만 이때, 크롬이나 파이어폭스에선 사용이 가능하지만 IE(Internet Explorer) 버전에서는 불가능 했다.

해결방안:

<div name='getname' id='getname'></div>

<div name='getname' id='getname'></div>

<div name='getname' id='getname'></div>

ID도 같이 줄 경우 해결되었다. 하지만 ID는 고유성을 가져야 하므로 불안한 느낌이 있다.




'Web > JavaScript' 카테고리의 다른 글

[Javascript] IE에서 addEventListener 사용  (0) 2013.08.21
[Javascript] 로딩바 구현  (0) 2013.08.20
[javascript] delay하고 처리하기  (0) 2013.08.17
[javascript] onload 시점 정리  (0) 2013.08.16

어느 정도 시간을 준 뒤에 자바스크립트를 처리하려 할때 사용할 수 있다.


setTimeout( function, mile second );

ex) setTimeout("helloworld()", 1000);    // 1000 mile second == 1 second


일정시간 딜레이만 주려면 아래와 같은 함수를 만들어 사용하면 된다.


function delay(gap){ /* gap is in millisecs */ 

  var then,now; 

  then=new Date().getTime(); 

  now=then; 

  while((now-then)<gap){ 

    now=new Date().getTime();  // 현재시간을 읽어 함수를 불러들인 시간과의 차를 이용하여 처리 

  } 




'Web > JavaScript' 카테고리의 다른 글

[Javascript] 로딩바 구현  (0) 2013.08.20
[Javascript] IE getElementsByName bug  (0) 2013.08.19
[javascript] onload 시점 정리  (0) 2013.08.16
[Javascript] IE setattribute 사용  (0) 2013.08.13


잘못 사용하면 많은 문제점이 따른다. 

먼저 onload는 DOM이 완성된 시점에서 실행된다.


<body onload = ""> 사용 시

<script> window.onload(){ 내용 } </script> 실행되지 않는다.

이에 대한 방안으로 window::onload() { 내용 } 을 사용할 수 있다.

실행순서 : body -> window::onload()


jQuery 활용하기

$(document).ready() 

DOM 데이터만 로드되면 바로 실행된다. 그러므로 window.onload 보다 빨리 실행된다.


jQuery를 이용한 실행 시점 순서이다.

$(window).load(function() { 모두 로드된 후에 처리 });

$(document).ready(function() { DOM객체 로드시 처리 });

$(function() { 로딩 될 때 });




문제 : IE의 9이하로는 javascript에서 setattribute가 실행되지 않는다. 


해결

var div1 = document.createElement("div");

var div2 = document.createElement("div");

div1.onclick = function() { alert("처리중 입니다. 잠시만 기다려주세요.") }

div2.onclick = function() { alert("처리중 입니다. 잠시만 기다려주세요.") }



코딩중에 도저히 내 머리로는 원인을 찾아볼 수 없는 버그가 있었다.

IE10에서는 실행이 되고 IE9에서는 실행이 안되는, 또한 내 컴퓨터에서는 되고 다른 컴퓨터에서는 안되는 문제.

도대체 어느 부분에서 문제가 되는지 머리를 쥐어잡고 찾아보았다.

평소에 console.log로 확인을 하면서 코딩을 하는데 다른 브라우저는 되고, IE9이하에서만 F12로 콘솔창을 띄우면 되고, 안띄운 상태에선 실행이 안되는 문제가 있었다.

콘솔창을 안띄우면 console객체가 정의되지 않은 상태여서 참조 할 수가 없어 console.log() 다음 코드는 실행되지 않는 것 같다.


  해결 방법으로, console.log() 전에 아래 코드를 넣어주면 된다. 조건문을 사용하여 console 객체가 없을 때, 생성하는 것이다.


if (!window.console) console = {log: function() {}};  


이번 경험을 통해 console.log 의 사용을 자제해야겠다... alert()으로 테스트해야지

브라우저별로 width, height 구할 때 다른 경우가 많아서 동일하게 적용할 수가 없다.

잘 정리된 코드가 있어서 어느때든 유용하게 사용할 수 있을 것 같다.


var w = 0, h = 0;

if (typeof (window.innerWidth) == 'number') { //Chrome

w = window.innerWidth / 2;

h = window.innerHeight / 2;

} else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {

w = document.documentElement.clientWidth / 2;

h = document.documentElement.clientHeight / 2;

} else if (document.body && (document.body.clientWidth || document.body.clientHeight)) { //IE9

w = document.body.clientWidth / 2;

h = document.body.clientHeight / 2;

}


출처 : http://ssamkj.tistory.com/3




수직정렬을 위하여 body 높이를 구할때 유용하게 사용할 수 있다.

body 높이 : document.body.scrollHeight


아래 코드로 브라우저의 높이와 폭도 간단하게 구할수 있다.

브라우저의 높이 : document.documentElement.clientHeight

브라우저의 폭 : document.documentElement.clientWidth


로딩 중 레이어(div) 띄우기, 만들기


저장이나 등록, 전송 버튼을 클릭 후 업로드 되는 동안 사용자가 버튼을 또 클릭하지 못하도록 버튼 클릭 시 레이어를 띄워서 클릭을 못하도록 가려둔다.

사용하는 방법은 버튼 클릭할 때 일어나는 ‘onclick’ 이벤트에서 일어나는 자바스크립트에 loading(1); 을 실행한다.

img_lo에 이미지를 미리 만들어주고, 미리 생성된 이미지를 화면에 포함시켜준다. 멈추는 경우가 발생할 수 있어 reloading_img()를 통해 실행하고 다시 이미지를 넣어준다.


수정사항

2013.08.09 z-index를 javascript에서 zIndex로 사용.

2013.08.12 console.log 버그를 찾고 수정하고 코드 정리함.

2013.08.27 멈추는 경우도 고려해 다시 수정.

var img_lo = document.createElement("span");
img_lo.innerHTML = "<img id="img_lo" src="./loading.gif" width="40" height="40">"

function loading(d) {	//변수 -> 이름,포지션 -> 높이,넓이 -> 마진,패딩 -> 위치 -> 기타
	if(d == 1) {
		var div_full = document.createElement("div");			// 화면 덮는 div
		var div_center = document.createElement("div");			// 센터 텍스트 담는 div
		var div_center2 = document.createElement("div");		// 센터 반투명 div
		var loading_text = document.createElement("p");			// 텍스트 p

		div_full.onclick = function() { alert("처리중 입니다. 잠시만 기다려주세요.") }
		div_center.onclick = function() { alert("처리중 입니다. 잠시만 기다려주세요.") }
	
		//var w = 0, h = 0;					// 크로스브라우징 높이,넓이 조절
		var w = '50%', h = '50%';				
	/*
			if (typeof (window.innerWidth) == 'number') { //Chrome
				 w = window.innerWidth / 2;
				 h = window.innerHeight / 2;
			} else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
				 w = document.documentElement.clientWidth / 2;
				 h = document.documentElement.clientHeight / 2;
			} else if (document.body && (document.body.clientWidth || document.body.clientHeight)) { //IE9
				 w = document.body.clientWidth / 2;
				 h = document.body.clientHeight / 2;
			}
	*/
		// 텍스트 태그 생성
		loading_text.style.height = "30";
		loading_text.style.width = "200";
		//loading_text.style.margin = "20px 0px 20px 0px";
		loading_text.style.margin = "15px 0px 15px 0px";
		loading_text.style.fontWeight = "bold";
		loading_text.innerHTML = "데이터 처리 중입니다.
잠시 기다려주십시오."; //전체 투명레이어 div_full.style.position = "absolute"; div_full.style.height = "100%"; div_full.style.width = "100%"; div_full.style.top = "0"; div_full.style.left = "0"; div_full.style.background = "#000000"; div_full.style.opacity = "0.0"; div_full.style.filter = "alpha(opacity=00)"; div_full.style.zIndex = "9995"; //이미지 중앙에 배치할 레이어 div_center.style.position = "absolute"; div_center.style.height = "100"; div_center.style.width = "200"; div_center.style.top = h; div_center.style.left = w; div_center.style.marginLeft = "-100px"; div_center.style.marginTop = "-50px"; div_center.style.textAlign = "center"; div_center.style.zIndex = "9998"; div_center2.style.position = "absolute"; div_center2.style.height = "100"; div_center2.style.width = "200"; div_center2.style.top = h; div_center2.style.left = w; div_center2.style.marginLeft = "-100px"; div_center2.style.marginTop = "-50px"; div_center2.style.background = "#ffffff"; div_center2.style.opacity = "0.8"; div_center2.style.filter = "alpha(opacity=80)"; div_center2.style.zIndex = "9996"; //포함시키기 div_center.appendChild(img_lo); div_center.appendChild(loading_text); document.body.appendChild(div_full); document.body.appendChild(div_center2); // 이미지는 투명도를 없애기 위해 다른 레이어를 바디에 포함. document.body.appendChild(div_center); // 이미지는 투명도를 없애기 위해 다른 레이어를 바디에 포함. } else if(d == 0) { div_full.parentNode.removeChild(div_full); div_center2.parentNode.removeChild(div_center2); div_center.parentNode.removeChild(div_center); } }

※ 자바스크립트에서는 CSS의 ‘z-index’를 사용할 때, ‘zIndex’로 사용해야 한다.


결론 :  나름 완성시킨 코드이지만 사용하면서 아직 문제점이 많을 것으로 보인다. 차근차근 코드를 수정해 나가야겠다.



'Web > JavaScript' 카테고리의 다른 글

[JS] 연산자 우선순위  (0) 2013.08.03
[JS] javascript 예약어  (0) 2013.08.02
[jQuery] Attribute Equals Selector [name="value"]  (0) 2013.07.16
[JS] 문자열 바꾸기 replace, 정규식  (0) 2013.07.05

 

window - location 객체

브라우저나 주소 표시줄과 관련되어 있어, 현재 문서에 대한 정보를 가지고 있다.

 

 프로퍼티

설명

location

객체의 프로퍼티

hash

책갈피 이름

host

URL과 호스트 이름, 포트 번호

hostname

URL과 호스트 이름

href

URL

pathname

링크의 경로

port

포트 번호

protocol

프로토콜

search

검색 엔진 노출

 

 

 

 메소드

설명

reload()

문서를 다시 읽어온다.(새로고침)

replace()

현재 문서를 다른 URL로 바꾼다.

 

 

 

 

+ Recent posts