728x90

        //정렬하고 1등에서 3등까지만 (배열에 남기고) 출력하시오.

 

function student(name, kor, eng, mat){//각 객체마다 prototype을 가지고 있다

                this.name = name;

                this.kor = kor;

                this.eng = eng;

                this.mat = mat;

        }

        

        student.prototype = {

                        getSum : function() {

                                return this.kor + this.eng + this.mat;

                        },

                        getAverage : function() {

                                return this.getSum()/3; //this = student객체

                        },

                        toString : function() {

                                 return this.name + '\t' + this.kor+'\t'+this.eng

                                        +'\t'+this.mat +'\t'+this.getSum()+'\t'+this.getAverage();

                                }

        }

        

        var students = [];

        students.push(new student("홍길동",90,80,70));

        students.push(new student("둘리",50,60,70));

        students.push(new student("또치",30,60,90));

        students.push(new student("뽀로로",10,40,20));

        students.push(new student("루피",0,60,70));

        students.push(new student("에디",40,40,40));

        students.push(new student("계란",50,60,30));

        //정렬하고 1등에서 3등까지만 (배열에 남기고) 출력하시오.

        

        var sortingField = "getSum()";

        

        students.sort(function(a,b) {

                return a[sortingField] > b[sortingField]? -1 : a[sortingField]<b[sortingField]?1:0;

        });     

        

        for(var i in students){

                document.write(students[i].toString()+"<br>");

        }

        

        var arr = students.splice(0,3);

        document.write(arr.toString()+ "<br>");

-->//정렬하고 1등에서 3등까지만 (배열에 남기고) 출력하시오.

          students = students.sort(function(a,b){

                     return b.getSum()-a.getSum(); //내림차순

          }).slice(0,3);

          

          var output = "이름\t국어\t영어\t수학\t총점\t평균\n";

          for(Var i in students){

                     output += students[i].toString() + '\n';

          }

          document.write(output);

**Event

-Event Handler : 이벤트가 발생했을 때 호출되는 함수

**innerHTML : 자식태그

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Insert title here</title>

<script type="text/javascript">

          //이벤트대상, 이벤트타입, 이벤트결과(핸들러)

          

          function doProcess(){

                     var result = document.getElementById("result");

                     result.innerHTML = "<span>이벤트 결과</span>"; //인라인방식

          }

          

          function doProcess2() { //스크립트방식

                     alert("이벤트 결과2");

                     

          }

          window.onload = function() {

                     var btn = document.getElementById("btn");

                     btn.onclick = doProcess2; //()쓰면 바로 호출되어버림, 이벤트등록

          }

</script>

</head>

<body>

          <input type = "button" value = "버튼1" onclick = "doProcess()">&nbsp;&nbsp;

          <input type = "button" value = "버튼2" id = "btn">

          <div id = "result"></div>

</body>

</html>

 

 

--eventListener

window.onload = function() {

                     var btn = document.getElementById("btn");

                     //btn.onclick = doProcess2; //이벤트등록

                     //btn.onclick = doProcess;

          

                     //btn.addEventListener('click',doProcess, false);

                     //btn.addEventListener('click',doProcess2, false);

                     

                     cross.Event.addListener(btn, 'click', doProcess2, false);

                     cross.Event.addListener(btn, 'click', doProcess, false);

                     }

//addEvent가 explore8에서는 작동안함(.js)

var cross = {}; //객체생성

cross.Event = {}; //cross안에 event객체 생성

cross.Event.addListener = function(element, name, handler, capture){ //크로스 브라우징 하려고 (구형 익스플로러에서 사용하기 위해)

          capture = capture | false;

          

          if(element.addEventListener){//표준브라우저 호출

                     element.addEventListener(name, handler, capture);

          }else{//구형 IE

                     element.attachEvent('on'+ name, handler);

          }

}

--부모자식관계 (e_exam02_1) 자식->부모 : eventBubbling / 부모->자식 : capturing

function doProcess(){

                     alert('aa');

          }

          

          function doProcess2() {

                     alert('bb');

                     event.stopPropagation();

          }

          

          window.onload = function() {

                     var a = document.getElementById("aa");

                     var b = document.getElementById("bb");

                     //a.onclick = doProcess;

                     //b.onclick = doProcess2;

                     

                     a.addEventListener('click',doProcess,false);

                     b.addEventListener('click',doProcess2,false);

                     

                     /* cross.Event.addListener(a, 'click', doProcess, false);

                     cross.Event.addListener(b, 'click', doProcess2, false); */

          }

</script>

</head>

<body>

          <div id="aa">

                     aaaaaaaaaaa

                     <div id="bb">

                               bbbbbbbbb

                     </div>

                     aaaaaaaaaaa

          </div>

--Bubbling 처리

cross.Event.stopBubble = function(event){

          if(event.stopPropagation){

                     event.stopPropagation();

          }else{

                     event.cancelBubble = true; //버블링 처리됨

          }

}

          function doProcess2(e) {

                     alert('bb');

                     

                     //이벤트 객체 구하기

                     var event = window.event || e; //e : 표준, window.event(옛날)

                     cross.Event.stopBubble(event);

          }

**mission03 : 가격계산

var sum = 0;

          var pre = 0;

          

          function calc(obj){ //eventhandler함수, click한 객체

                     if(obj.type == 'checkbox'){

                               if(obj.checked == true) {

                                         sum += parseInt(obj.value);

                               }else{

                                         sum -= parseInt(obj.value);

                               }

                     }else{

                               sum -= pre;

                               sum += parseInt(obj.value);

                               pre = parseInt(obj.value);

                               }         

                               document.fmt.result.value = sum;

                     }

                     

          

          window.onload = function(){

                     var inputs = document.getElementsByTagName("input");

                     for(var i=0;i<inputs.length;i++){

                               //inputs[i].onclick = calc;

                               inputs[i].onclick = function(){ //자기자신을 넘겨여 하므로 함수사용

                                         calc(this); //내가 클릭한 것

                               }

                     }

          }

          

</script>

</head>

<body>    

<form name="fmt">

          두부 400원

          <input type="checkbox" value="400" >

          콩나물 150원

          <input type="checkbox" value="150">

          간장 1500원

          <input type="checkbox" value="1500">

          <br><br>

          퀵 서비스

          <input type="radio" name="del" value="5000">

          택배

          <input type="radio" name="del" value="2500">

          <br><br>

          

          지불하실 금액은 : <input type="text"" name="result">

**mission04 - 이미지바꾸기

function change(obj) {

                     var img = document.getElementById("default");

                     img.src = obj.src;

                     

}

window.onload = function() {

          var img = document.getElementById("default");

          var defaultImg = img.src;

          

          var imgs = document.getElementsByTagName('img');

          for(var i=0;i<imgs.length;i++){

                     imgs[i].onmouseover = function(){ //자기자신을 넘겨여 하므로 함수사용

                               change(this); //내가 클릭한 것 , **this : 이벤트대상

                               }

                     imgs[i].onmouseout = function(){

                               img.src = defaultImg;

                               }

                     }

}

</script>

</head>

<body>

<center>

<h2>고양이 앨범</h2>

<img id = "default" src = "../images/cat0.jpg" border = "1" width = "600" height = "450"></img>

<br/><br/><br/>

<img src = "../images/cat1.jpg" width = "70" height = "70" border = "1" hspace = "10" vspace = "10"></img>

<img src = "../images/cat2.jpg" width = "70" height = "70" border = "1" hspace = "10" vspace = "10"></img>

<img src = "../images/cat3.jpg" width = "70" height = "70" border = "1" hspace = "10" vspace = "10"></img>

</center>

**this


var data = 10;

          

          function outer() {

                     this.data = 20; //일반함수 안에서의 this = window객체

                     data = 30;

                     

                     console.log("1. data:" + data); //30

                     console.log("2. this.data:" + this.data); //30

                     console.log("3. window.data:" + window.data);  //30

          }

          outer();


var data = 10;

          

          function MyClass() { //생성자함수 안의 this = 해당객체자신

                     this.data = 0;

          }

          MyClass.prototype.method1 = function() {//프로토타입함수 안의 this = 해당객체자신

                     this.data = 20;

                     data = 30;

                     

                     console.log("1. data:" + data); //30

                     console.log("2. this.data:" + this.data);  //20

                     console.log("3. window.data:" + window.data);   //30

          }

          

          var m1 = new MyClass();

          m1.method1();

          


var data = 10;

        

        window.onload = function() {

                var btn = document.getElementById("btn");

                btn.onclick = function () { //이벤트 핸들러함수

                        this.data = 20; //this = 클릭한 button(이벤트대상)

                        data = 30;

                        

                        console.log("1. data:" + data); //30

                        console.log("2. this.data:" + this.data);  //20

                        console.log("3. window.data:" + window.data);   //30

                }

        }

 


var data = "Global data";

          var obj1 = {'data' : 'obj1 data'};

          var obj2 = {'data' : 'obj2 data'};

          function func() {

                     console.log(this.data); //윈도우 객체

          }

          //func();

          func.apply(obj1); //window객체였던 this를 obj1객체로 change하기 위함

 

 

 

**window객체

--ex1

function winOpen(){

                     window.open("address.html","주소검색창", "width=300, height=300");

          }

</script>

</head>

<body>

          <form name = "fmt">

                     주소 : <input type = "text" name = "addr">

                     <input type = "button" value = "주소" onclick="winOpen()">

          </form>

 

--address

          window.onload = function() {

                     var links = document.getElementsByTagName("a");

                     for(var i=0; i<links.length;i++){

                               links[i].onclick = function(){

                                         window.opener.document.fmt.addr.value = this.innerHTML; //자식입장에서 부모윈도우객체 사용가능(HTML은 돔객체로 생성되어 있기 때문)

                                         self.close();

                               }

                     }

          }

</script>

</head>

<body>

          <ul>

                     <li><a href = "#">서울특별시 강남구 대치동</a></li>

                     <li><a href = "#">서울특별시 금천구 가산동</a></li>

                     <li><a href = "#">경기도 성남시 판교동</a></li>

          </ul>

 

 

 

**DOM

 

 

 

 

 

--gallary01

          //기본이벤트 취소하는 방법 : return false;

          

          

          function showPic(obj){

                     var source = obj.getAttribute("href");

                     var placeholder = document.getElementById("placeholder");

                     placeholder.setAttribute("src",source);

                     

                     var text = obj.getAttribute("title");

                     var description = document.getElementById("description");

                     

                     if(description.firstChild.nodeType == 3){ //노드의 자식노드가 텍스트(3)인지

                               description.firstChild.nodeValue = text;

                     }

                     

                     /* var img = document.getElementById("placeholder");

                     img.src = obj.href;

                     

                     var text = document.getElementById("description");

                     text.innerHTML = obj.title; */

                     

          }

          

                     

          

          

</script>

</head>

<body>

          <h1>gallery</h1>

          <ul>

                     <li>

                               <a href="images/fireworks.jpg" title="A fireworks dispaly"

                                                   onclick="showPic(this); return false;">Fireworks</a>

                     </li>

                     <li>

                               <a href="images/coffee.jpg" title="A cup of black coffee"

                                                   onclick="showPic(this); return false;">Coffee</a>

                     </li>

                     <li>

                               <a href="images/rose.jpg" title="A red red rose"

                                                   onclick="showPic(this); return false;">Rose</a>

                     </li>

                     <li>

                               <a href="images/bigben.jpg" title="The famous clock"

                                                   onclick="showPic(this); return false;">Big Ben</a>

                     </li>

          </ul>

          <img id="placeholder" src="images/placeholder.gif" alt="myImage"/>

          <p id="description">Choose an image</p> <!-- 부모자식관계 -->

 

 

 

 

 

 

 

 

728x90

+ Recent posts