1. window 객체

전역객체

자바스크립트의 모든 객체는 window 객체의 하위 객체로서 존재한다.

그러므로 내장 객체에 대한 접근 방법은 window.내장객체이름.함수이름();이 올바르나,

모든 객체가 window 안에 내장되어 있기 때문에, window 객체를 명시적으로 선언하는 것은 생략이 가능하다.

내장객체이름.함수이름();

 

  • BOM(Browser Object Model)
    웹 브라우저의 창이나 프레임을 추상화해서 프로그래밍적으로 제어할 수 있도록 제공하는 수단이다.
  • DOM(Document Object Model)
    BOM 소속인데, 자주 사용되고 중요한 객체여서 따로 분리되었다.
  • JavaScrip
    웹에서 쓰일 때 사용되는 프로퍼티, 객체들  

 

 

 

1-1. window.open() 함수

JavaScript 모든 기능이 window 객체의 하위기능이기도 하지만, 그 중 브라우저의 창을 제어하는 것과 관련된 open() 함수가 window 객체에 직접적으로 포함되어 있다.

<h1>window 객체</h1>
<h3>open 메소드 확인</h3>
<div>
    <a href="#" onclick = "open1(); return false;">새창열기</a>
    <br/>
    <a href="#" onclick = "open2(); return false;">팝업열기</a>
    <br/>
    <a href="#" onclick = "open3(); return false;">팝업열기2</a>
</div>

// 새로운 창 열기
// window.open("페이지 url")
function open1(){
        window.open('http://www.naver.com');
}

// 팝업창 형태로 창을 열 경우
// window.open("페이지url", "창이름", "옵셥")
function open2(){
    window.open('http://www.naver.com', '', 
            'width=300, height=500, scrollbars=no,toolbar=no, menubar=no, status=no, location=no');
}

// 한 번 생성된 팝업창을 지속적으로 재사용하는 팝업창
function open3(){
    window.open('http://www.naver.com', 'mywin', 
            'width=300, height=500, scrollbars=no,toolbar=no, menubar=no, status=no, location=no');
}

 

[출력 결과]

 

 

 

1-2. Location 객체

Location 객체는 웹 브라우저의 주소 표시줄을 제어한다.

document.write("<p>문서의 url 주소 : " + location.href + "</p>");
// 웹페이지 기본 port는 80번이고 80번은 조회가 되지 않는다.
document.write("<p>호스트 이름과 포트 : " + location.host + "</p>");
document.write("<p>프로토콜 종류 : " + location.protocol + "</p>");
document.write("<p>URL 조회 : " + location.search + "</p>");
document.write("<p>디렉토리 이하 경로 : " + location.pathname + "</p>");

 

[출력 결과]

 

[예제 코드]

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<input type="button" value="네이버로 이동하기" onclick="goNaver()"/>
	<script>
		function goNaver(){
			location.href = "http://www.naver.com";
		}
	</script>
</body>
</html>

▶ 네이버로 이동하기 버튼을 클릭하면 location.href에 명시한 주소로 이동한다.

 

[실습 코드]

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<!-- onload : 페이지 최초 로딩시, authNo() 함수를 호출 -->
<body onload="authNo()">
	<!-- 
		문제. 0~9 사이의 랜덤 5자리 인증번호를 id값이 "auth"인 요소에서 출력
		document.getElementById("auth").innerHTML = 랜덤숫자;
	 -->
	<p>
		고객님의 인증번호는 <strong id ="auth">00000</strong>입니다.
	</p>
	
	<input type="button" value="인증번호 새로 받기" onclick="refresh();"/>
	
	<script>
		function refresh(){
			// location 객체 안에 포함된 reload()함수는 현재 페이지를 새로고침한다.
			location.reload();
		}
		
		// 두 수 사이의 랜덤값을 리턴하는 함수
		function random(n1, n2){
			return parseInt(Math.random()*(n2 - n1 + 1)) + n1;
		}
		
		// 5가지 인증번호 return해주는 함수
		function authNo(){
			let value = "";
			for(let i = 0 ; i<5; i++){
				value += random(0,9);
			}
			
			document.getElementById("auth").innerHTML = value;
		}
	</script>
</body>
</html>

 

[출력 결과]

▶ 페이지 최초 로딩시 authNo() 함수를 실행한다.

▶ '인증번호 새로 받기' 버튼을 클릭하면 refresh() 함수를 실행하여 페이지를 새로고침한다.

▶ 페이지가 새로고침되면서 다시 authNo() 함수가 실행된다. 

 

 

 

1-3.history 객체

history 객체는 브라우저의 "뒤로", "앞으로" 버튼의 기능을 수행하는 객체로써, back() 함수와 forward() 함수를 내장하고 있다.

  • 이전 페이지로 이동하기 : history.back();
  • 다음 페이지로 이동하기 : history.forward();

 

[예제 코드]

- window5.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>History 객체</h1>
	<a href="history.html">페이지 이동</a><br>
	<a href="#" onclick="history.forward(); return false;">
		앞 페이지로 이동
	</a>
</body>
</html>

 

- history.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>History 객체</h1>
	<a href="#" onclick="history.back(); return false;">
		이전 페이지로 이동
	</a>
</body>
</html>

 

[출력 결과]

▶ 페이지 이동 클릭 시 <a href>로 지정한 history.html로 페이지가 이동된다.

▶ 이전 페이지로 이동 클릭 시 history.back() 함수가 실행되어 window5.html로 돌아온다.

▶ window5.html에서 앞페이지로 이동 클릭 시 history.forward() 함수가 실행되어 앞페이지(history.html)로 돌아간다.

 

 

 

1-4. navigator

브라우저의 정보를 조회하는 내장 객체

하나의 웹서비스로 다양한 브라우저를 지원할 수 있도록 처리하기 위한 기본이 되는 정보를 추출할 수 있다.

  • navigator.appName : 브라우저 이름
  • navigator.appCodeName : 브라우저 코드명
  • navigator.platform : 플랫폼 정보
  • navigator.appVersion : 브라우저 정보
  • navigator.userAgent : 사용자 정보

 

 


 

 

2. document

2-1. document.getElementsByTagName

문서 내에서 특정 태그에 해당되는 객체를 찾는 방법은 여러가지가 있다.

인자로 전달된 태그명에 해당하는 객체들을 찾아서 그 리스트를 유사배열에 담아서 반환한다.

 

[예제 코드 1]

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	 <ul>
	 	<li>HTML</li>
	 	<li>CSS</li>
	 	<li>JavaScript</li>
	 </ul>
	 
	 <script>
	 	let list = document.getElementsByTagName("li");
	 	for(let i = 0; i < list.length; i++){
	 		list[i].style.color = 'tomato';
	 	}
	 </script>
</body>
</html>

 

[출력 결과 1]

 

[예제 코드 2]

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<ul>
		<li>HTML</li>
		<li>CSS</li>
	 	<li>JavaScript</li>
	</ul>
	<ol>
		<li>HTML</li>
		<li>CSS</li>
	 	<li>JavaScript</li>
	</ol> 
    
	<script>
		let ul = document.getElementsByTagName('ul')[0];
		let lis = ul.getElementsByTagName('li');
		for(let i = 0; i < lis.length; i++){
			lis[i].style.color = 'tomato';
		}
	</script>
</body>
</html>

▶ ul 태그에서도 1depth 더 들어가 li 태그 지정 후 스타일 준 형태

 

[출력 결과 2]

 

 

 

2-2. document.getElementsByClassName

class 속성의 값을 기준으로 객체를 조회

 

[예제 코드]

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<ul>
		<li>HTML</li>
		<li class = "active">CSS</li>
	 	<li class = "active">JavaScript</li>
	</ul>
	
	<script>
		let lis = document.getElementsByClassName('active');
		for (let i = 0; i < lis.length; i++) {
			lis[i].style.color = 'powderblue';			
		}
	</script>
</body>
</html>

 

[출력 결과]

 

 

 

2-3. document.getElementById

id 값을 기준으로 객체를 조회한다. 성능면에서 가장 우수

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<ul>
		<li>HTML</li>
		<li id = "active">CSS</li>
	 	<li>JavaScript</li>
	</ul>
	
	<script type="text/javascript">
		let li = document.getElementById('active');
		li.style.color = 'tomato';
	</script>
</body>
</html>

 

[출력 결과]

 

728x90

'이론 > 자바 풀스택 국비수업' 카테고리의 다른 글

220517 Javascript 11  (0) 2022.06.23
220513~16 Javascript 10  (0) 2022.06.23
220512 Javascript 8  (0) 2022.06.22
220512 Javascript 7  (0) 2022.06.22
220511 Javascript 6  (0) 2022.06.22

+ Recent posts