728x90

 

Window Object(윈도우 객체)

브라우저 창에 대한 설정을 하는 객체

 

window객체는 자바스크립트의 최상위 객체, BOM/DOM으로 나뉨

BOM(Browser Object Model) : 브라우저에 관련된 객체. ex) location, navigator, history, screen객체

DOM(Document Object Model) : document객체. 문서 자체에 관계가 있는 모델들을 담아둠

 

 

window.open()

브라우저 새로 띄우기

window.open(주소창, 열려는 창 이름, 넓이, 높이)

window.open 반환값 새로 만들어진 창 객체가 반환됨. 창의 생성에 실패하면 null을 반환 이 객체를 통해서 새창을 제어할 수 있다. 예로 popup.close() 로 창을 닫기 가능

function test1() {
  // window.open();                            // 비어있는 새탭이 열림
  // window.open("01_JavaScript.html");        // 01번html문서 열림
  // window.open("<http://www.naver.com>");      // 네이버 열림
  window.open('<http://www.naver.com>', '네이버', 'width=500, height=300');      
// 네이버 열림 + 팝업 + 창크기 지정 // '네이버' : 창에 대한 이름 지정 // 크기지정하면 해당 크기의 팝업으로 뜸

}

 

 

popup.document.write()

팝업 창 띄우기

function test2() {          
// var popup = window.open('', '', 'width=300, height= 200'); // 비어있는 팝업창이 뜸                
popup.document.write('<html><body><h2>짜잔! 새로운 팝업 탄생잉요!</h2></body></html>');
}

 

window객체의 timer메소드

setTimeout()

몇 밀리초 후에 함수를 호출

function test3(){
  window.open(', ', 'width=500, height=300');

  myWindow.alert('3초 후에 이 페이지는 종료됩니다.'); // myWindow 팝업창에 안내창 뜸 
  
  // 알림창 3초 후에 제거
  // window.setTimeout()
  
  myWindow.alert('3초 후에 이 페이지는 종료됩니다.');
  // myWindow 팝업창에 안내창 뜸 
  window.setTimeout(function() {
          myWindow.close();   // // 닫아줌 언제? 3초 뒤에 (1초 = 1000)
  },3000);
}

close() : window를 닫음

 

 

setInterval()

지정한 시간마다 매개변수로 넘겨준 함수를 실행

// 목적 : 버튼을 누르지 않아도 시간이 실시간으로 바껴서 화면에 보이는 것
function test4() {
    var area4 = document.getElementById('area4');

    // window.setInterval()
    **window.setInterval**(function(){
    var date = new Date();      // 시간을 나타낼거라고 했으니. 시간을 나타내는 객체 date
    area4.innerHTML = date.getHours() + " : " + date.getMinutes() + " : " + date.getSeconds();                              
    // 밸류가 아니니 innerHTML
    }, 1000); // 시간이 바뀌는 기준 1초 // 1000 1초마다 내용 바뀌게 할 것이니 단위는 1000

 

 

new Date()

시간을 나타내는 객체 Date

var date = **new Date()**;      // 시간을 나타낼거라고 했으니. 시간을 나타내는 객체 date
area4.innerHTML = date.**getHours**() + " : " + date.**getMinutes**() + " : " + date.**getSeconds**();                              
// 밸류가 아니니 innerHTML
728x90
반응형
728x90

 

document.write()
console.log()

 

innerHTML
window.confirm()
window.prompt()
getElementById()
getElementsByName()
 
 
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">

<title>cheer up</title>


<style>
	.area{width: 300px; height: 100px; border: 1px solid blue;}
</style>

</head>
<body>

    <script>
        document.write("혼자출력");
        console.log;    // 노에러 작동x
        console.log(document.write("콘솔출력")); // undefined
        console.log("document.write() : 콘솔 출력"); // 콘솔 출력 : a
        // 값이 대입되지 않은 변수 혹은 속성을 사용하려고 하면 undefined를 반환
    // JavaScript에는 '없음'를 나타내는 값이 두 개 있는데, 
    // 바로 null와 undefined입니다. 두 값의 의미는 비슷하지만, 
    // 각각이 사용되는 목적과 장소가 다릅니다
    // null은 '객체가 없음'

    // https://helloworldjavascript.net/pages/160-null-undefined.html
    // ? 왜 address null 넣는걸 잘 안하지? 명시적인게 더 낫지않나?
        
    </script>

    <script>
        // alert('알림창띄워보기');
        // window.alert("win 생략가능");
    </script><br>

    
    <button onclick="doCon();">console.log() : 콘솔창 출력</button>
    <script>
        function doCon(){
            console.log("클릭하면 함수 실행")   // 클릭하면 함수 실행
            window.console.log("정석은 window.console.log()")
        }
    </script>
    
    <h4>innerHTML</h4>
    <div id="inner2">innerHTML : 태그 엘리먼트의 값을 읽거나 변경할 때 innerHTML 속성 사용<br>
        누르면 div 내용 사라지고
    </div>
    <p>p태그도 사라지나? 유지되고 div 내용만 사라지고<br>
        in2.innerHTML = " "에 담긴 내용이 출력됨
    </p>
    <button onclick="innerHTML2();">데이터출력 - innerHTML()</button>
    <script>
        function innerHTML2(){
            var in2 = document.getElementById("inner2");
            console.log(in2);
            console.log(typeof in2); // in2타입:object
            // console.log(in2.innerHTML);
            in2.innerHTML = 'innerHTML 동작 성공'; // 즉, innerHTML은 object를 읽어온 것
        }
    </script>

    <h3>데이터 입력</h3>
    <h4>window.confirm : Y/N 질문창. 확인버튼은 true, 취소 버튼은 false 반환 </h4>
    <button onclick="testconfirm();">데이터입력 - window.confirm()</button>
    <script>
        function testconfirm(){
            var cfm = window.confirm('확인과 취소 창');
            console.log(cfm); // 확인은 true받았고 취소는 false받음

            if(cfm){
                console.log("확인 누름"+cfm);
                alert("확인 누름"+cfm);
            }else{
                console.log("취소 누름"+cfm);
                alert("취소 누름"+cfm);
            }
            var cheerUp = window.confirm("힘내고 있니?");
            alert(cheerUp);
        }
    </script>

    <h4>window.prompt</h4>
    <div class="area">div inner2</div>
    <p>
        텍스트 필드와 확인, 취소 버튼이 있는 대화상자  
        입력한 메세지 내용을 리턴받음
    </p>
    <button onclick="testPrompt();">데이터출력 - window.prompt()</button>
    <script>
        function testPrompt(){
            var prom = window.prompt("window.prompt() 창 떴는가?");
            console.log(prom);  // a누르고 a를 반환받아 var prom에 저장
            console.log(typeof prom);  // str
            prom.innerHTML = "메세지 저장완료"; // prom이 str이라 안되는듯

        }
    </script>



    <h2> ▷html태그에 접근하기◁</h2>
    <h3>아이디로 접근 : getElementById()</h3>
    <div id="gebyId1">getElementById()</div>
    <button onclick="testGetelementById();">html태그 접근 - 아이디 - getelementByid() </button>
    <script>
        function testGetelementById(){
            var byId1 = document.getElementById('gebyId1');
            console.log(byId1);
            console.log(typeof(byId1));
            byId1.innerHTML = '변수는 오브젝트'; // div내용이 '변수는 오브젝트'로 변경됨
            // innerHTML, div의 id를 읽어왔기에 그 내용을 변경한 듯?
            // name에서도 이어서 테스트

        }
    </script>

    <h3>name으로 접근</h3>
    <p>
        getElementsByName() : 반환타입 [] Node list
        해당 name 속성값을 가지는 요소를 모두 선택함.
    </p>
    <form>
		<fieldset>
			<legend>취미</1egend>
			<table>
				<tr>
					<td><input type="checkbox" name="hobby" value="game1" id="game2"><label>게임</label></td>
					<td><input type="checkbox" name="hobby" value="music1" id="music2"><label>음악</label></td>
					<td><input type="checkbox" name="hobby" value="movie1" id="movie2"><label>영화</label></td>
				</tr>
				<tr>
					<td><input type="checkbox" name="hobby" value="book1" id="book2"><label>독서</label></td>
					<td><input type="checkbox" name="hobby" value="travel1" id="travel2"><label>여행</label></td>
					<td><input type="checkbox" name="hobby" value="exercise1" id="exercise2"><label>운동</label></td>
				</tr>
			</table>
		</fieldset>
	</form>
    <div id="byname1" class="area">getElementsByName() : 반환타입 [] list</div>
    <button onclick="testByname1();">데이터접근 - name접근 - getElementsByName()</button>
    <script>
        function testByname1(){
            var tbn1 = document.getElementsByName('hobby');
            console.log(tbn1);  // NodeList(6) <- table 6개<td>데이터수 // input#game2는 각 input태그의 id
            console.log(typeof tbn1); // object
    
            var checkName='';
            for (var i = 0; i < tbn1.length; i++){
                checkName = tbn1[i].value + "선택함<br>";
            }
            byname1.innerHTML = checkName;  // 54 // 비추천방법
            document.getElementById('byname1').innerHTML=checkName; // 54
        }
    </script


</body>
</html>
728x90
반응형

+ Recent posts