HTML5, CSS3/Java Script

23-02-24 JS

모건이삼촌 2023. 2. 24. 17:42

4-4) concat

 - 2개이상의 배열을 하나의 배열로 결합 (자바의 addAll)

 

4-5) slice()

 - 

 

4-6)sort()

 - 배열에 문자형 데이터 있는경우 오름차순 정렬

 - 

 

arr = [
  {name:'김', score:50},
  {name:'이', score:70},
  {name:'박', score:90},
  {name:'최', score:30},
  {name:'정', score:1},
  {name:'전', score:11},
  {name:'양', score:12}
]
arr.sort(function(a, b){
  return b.score - a.score 
});
arr.reverse

arr=[1, 13, 10, 5, 6, 4]; // 문자타입으로 인식해 문제발생
arr.sort(function(a, b) {return a-b});
console.log(arr);

 4-7) filter() (나중에 함)

 - 특정 조건을 만족하는 배열의 요소만을 찾아서 새로운배열로 반환

 - 

 

 - 파라미터와 리턴이 없을 때

 

 * 컨슈머 (Consumer)

  - 1개의 입력값 반환값 없음

 * 바이컨슈머 (BiConsumer)

  - 2개의 입력값 반환값 없음

 * 서플라이어 (supplier)

  - 입력값 없음 반환값 있음

 * function

 - 1개의 입력값, 반환값 있음

 

1. Date 객체

 - 날짜와 시간을 다루는 객체

 

1-1) Date 생성자

 - Date객체는 4가지 방법으로 생성할 수 있다. (p.128)

 

1-2)Get 함수 

p.129 표 삽입

 

1-3) Set 함수

 

2. Set 객체

 - 배열처럼 값들의 집합

 - 데이터타입에 상관없이 추가할 수 있음.

 - 중복값을 허용하지 않음

 - 

let set = new Set();
set.add(3);
set.add(1);
set.add(2);
set.add(6);
// set.sort(); //지원 안함
set.forEach(function (a) {console.log(a)});
// console.log(set);

3. Map 객체 (잘 안씀)

let obj = {a:1, b:2};
let m = new Map();
m.set("a", 1);
m.set("b", 2);
console.log(m);
console.log(m.get("a")); // 1
console.log(m.a);

let s = m.entries();
console.log(s);

4. Math객체

 - 수학적인 상수와 내장함수를 가진 객체

 - Math는 생성자가 아님

 - 숫자자료형만 지원

function max() {
  // console.log(arguments);
  let ret = arguments[0];
  for(let i in arguments) {
    if(ret < arguments[i]) {
      ret = arguments[i];
    }
  }
  return ret
}
console.log(max (10, 20, 30, 40, 0, -10));

실습) 가위바위보 게임

<!DOCTYPE html>
<html>
<head>
  <meta charset='utf-8'>
  <meta http-equiv='X-UA-Compatible' content='IE=edge'>
  <title>Page Title</title>
  <meta name='viewport' content='width=device-width, initial-scale=1'>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.3/jquery.min.js" integrity="sha512-STof4xm1wgkfm7heWqFJVn58Hm3EtS31XFaagaa8VMReCXAkQnJZ+jEy8PCC/iT18dFy95WcExNHFTqLyp72eQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  <script>
    $(function() {
      let record = {t:0, w:0, d:0, l:0};
      $(":radio").click(function() {
        // $("p").eq(0).find("span").text($(this).parent().text())
        // console.log($(this).data("val"));
        let my = $(this).data("val")
        let you = parseInt(Math.random()*3)
        let result;
        
        switch(my-you) {
          case 0 :
            record.d++;
            result = "무승부!";
            break;
          case 1 : case -2 : 
            record.w++;
            result = "승리!";
            break;
          case -1: case 2:
            record.l++;
            result = "패배!";
        }
        record.t++
        let arr = ['가위', '바위', '보'];

        $("p").eq(0).find("span").text(arr[my]);
        $("p").eq(1).find("span").text(arr[you]);
        $("p").eq(2).find("span").text(result);
        $("p").eq(3).find("span").text(
            record.t + "전" 
          + record.w + "승" 
          + record.d + "무" 
          + record.l + "패" 
          + "승률" + (record.w / record.t * 100).toFixed(2) + "%"
          );
      })
    })
  </script>
</head>
<body>
  <label>가위<input type="radio" name="srp" data-val="0"></label>
  <label>바위<input type="radio" name="srp" data-val="1"></label>
  <label>보<input type="radio" name="srp" data-val="2"></label>
  <p>당신의 패 <span> </span></p>
  <p>상대방의 패 <span> </span></p>
  <p>결과 <span> </span></p>
  <p>전적 <span> </span></p>
</body>
</html>

 

4. JSON 객체 p.142

 - 데이터를 저장하거나 전송할 때 많이 사용되는 경량의 DATA교환 형식

 - JSON은 데이터 포맷일 뿐이며 특정 통신 방법도, 프로그래밍 문법도 아닌 단순히 데이터를 표시하는 방법

 

5. window 객체

 5-1) open

<!DOCTYPE html>
<html>
<head>
  <meta charset='utf-8'>
  <meta http-equiv='X-UA-Compatible' content='IE=edge'>
  <title>Page Title</title>
  <meta name='viewport' content='width=device-width, initial-scale=1'>
  <script>
    // open(url, name, spec, replace)
    // open("") // 탭
    let test = open("", 'aaa' ,'width=400, height=300') // 새 창
    console.log(test);
    test.document.write("<h1>hello java</h1>")
  </script>
</head>
<body>
  
</body>
</html>

5-2) setTimeout, clearTimeout(), setInterval(), clearInterval()

    window.onload = function() {
      document.getElementById("time").innerText = new Date();
      var inter = setInterval(function() {
        document.getElementById("time").innerText = new Date();
      },1000)

      setTimeout(function(){
        clearInterval(inter);
      },10000)
    }

5-3) symbol

 

※ js html DOM (p.222)

 -

 - 트리구조로 구성된다

 

1. DOM Element(요소)

 

1-1) html요소의 id로 html요소 찾기.

 

1-2) DOM Attribute

  - 자바의 getter, setter랑 비슷함

  - 속성을 부여하거나, 읽어오거나

    console.log(userid.title);
    console.log(userid["title"]);
    console.log(userid.getAttribute("title"));

    userid.abcd = "1234";
    userid.title = "변경된 타이틀";
    userid["title"] = "변경된 타이틀2";

    userid.setAttribute("abcd","1234");

 

예제)

<!DOCTYPE html>
<html>
<head>
  <meta charset='utf-8'>
  <meta http-equiv='X-UA-Compatible' content='IE=edge'>
  <title>Page Title</title>
  <meta name='viewport' content='width=device-width, initial-scale=1'>
  <style>
    table {width: 800px; margin: 0 auto;}
    th + th + th {width: 500px;}
    th + th + th + th {width: 100px;}
  </style>
</head>
<body>
  <table border="1">
    <tr>
      <th>
        <input type="checkbox">
      </th>
      <th>발송자</th>
      <th>제목</th>
      <th>시간</th>
    </tr>
    <tr>
      <td><input type="checkbox"></td>
      <td>더조은아카데미</td>
      <td>출결 안내 사항</td>
      <td>2023-01-11</td>
    </tr>
    <tr>
      <td><input type="checkbox"></td>
      <td>더조은아카데미</td>
      <td>출결 안내 사항</td>
      <td>2023-01-11</td>
    </tr>
    <tr>
      <td><input type="checkbox"></td>
      <td>더조은아카데미</td>
      <td>출결 안내 사항</td>
      <td>2023-01-11</td>
    </tr>
  </table>
  <script>
    let chk = document.querySelector("th input");
    chk.onchange = function() {
      let flag = this.checked; // 
      let chks = document.getElementsByTagName("input");
      for(let i in chks) {
        chks[i].checked = flag;
      }
      // if(flag) {
      //   for(let i in chks) {
      //     chks[i].setAttribute("checked", "");
      //   }
      // }
      // else {
      //   for(let i in chks) {
      //     chks[i].removeAttribute("checked");
      //   }
      // }
    }
  </script>
</body>
</html>

2. HTML 내용 변경

 2-1) innerHTML (이것만 잘 써도 된당)

  - HTML의 특정 위치에 새로운 HTML을 삽일할 때 innerHTML을 사용할 수 있다.

 2-2)innerText

 

3. DOM 이벤트 (~할 때 라고 알면 편함

)

 - 사용자가 웹페이지를 이용하면서 행하는 액션을 이벤트라고 한다

 

3-1) click 이벤트

 - 마우스 버튼을 클릭할 때 발생하는 이벤트

 - 

<!DOCTYPE html>
<html>
<head>
  <meta charset='utf-8'>
  <meta http-equiv='X-UA-Compatible' content='IE=edge'>
  <title>Page Title</title>
  <meta name='viewport' content='width=device-width, initial-scale=1'>
  
</head>
<body>
  <!-- 
    이벤트 대상(타겟, 객체)
    이벤트 속성(이름)
    이벤트 핸들러, 리스너
   -->
   <!-- 인라인 이벤트 onclick="alert(this.innerText) 권장하지않음 -->
   <button type="button" onclick="fn()">click me</button>
   <script>

    
    function fn () {
      alert(10);
    }
    let btn = document.querySelector("button")

    // 일반 이벤트 적용
    // btn.onclick = function(e) {
    //   alert(20);
    // }
    // btn.onclick = function(e) {
    //   alert(30);
    // }

    // 표준 이벤트 적용(standard event)
    btn.addEventListener("click",function(e){
      alert(40);
    });
    btn.addEventListener("click",function(e){
      console.log(e === event);
      console.log(event);
    });
  </script>
</body>
</html>

* 기본이벤트, 이벤트 전달 (아래 링크 참고)

https://developer.mozilla.org/ko/docs/Web/API/EventTarget/addEventListener

 - 기본이벤트 : a태그, form태그, submit 등등

 - 이벤트 전달 : 이벤트 한곳에 이벤트가 여러개 있는것

예제) ↓ 이벤트 버블링(자식쪽에서 조상쪽으로 이동 / 반대는 캡쳐링)

<!DOCTYPE html>
<html>
<head>
  <meta charset='utf-8'>
  <meta http-equiv='X-UA-Compatible' content='IE=edge'>
  <title>Page Title</title>
  <meta name='viewport' content='width=device-width, initial-scale=1'>
  <style>
    div, h3 {border: 2px solid; padding: 30px;}
  </style>
</head>
<body>
 <div onclick="alert(1)">
    <div onclick="alert(2)">
      <div onclick="alert(3)">
        <h3 onclick="alert(4)">안녕하세요</h3>
      </div>
    </div>
   </div>
   </body>
</html>

3-2) change 이벤트

 - 

 

3-3) focus 이벤트

 - 

* html의 input type="focus"

 

예제) focus, blur 이벤트 혼합예제

<!DOCTYPE html>
<html>
<head>
  <meta charset='utf-8'>
  <meta http-equiv='X-UA-Compatible' content='IE=edge'>
  <title>Page Title</title>
  <meta name='viewport' content='width=device-width, initial-scale=1'>
</head>
<body>
  <form name="frm">
    <input name="userid" id="id" autofocus>
    <input name="password" id="pw" type="password">
    <button name="btnLogin">로그인</button>
  </form>  
  <p id="result"></p>
  <p id="result2"></p>
  <script>
    let form = document.frm;
    frm.onsubmit = function() {
      event.preventDefault();
    }
    let focusTarget = document.querySelectorAll("form > *");
    focusTarget.forEach(function(item){
      item.onfocus = function() {
        document.getElementById("result").innerHTML = this.name + " focused in";
      }
      item.onblur = function() {
        document.getElementById("result2").innerHTML = this.name + " focused out"
      }
    })
  </script>
</body>
</html>

 

3-4) key 이벤트 (onketdown, onkeypress, onkeyup)

 

예제 총합)

<!DOCTYPE html>
<html>
<head>
  <meta charset='utf-8'>
  <meta http-equiv='X-UA-Compatible' content='IE=edge'>
  <title>Page Title</title>
  <meta name='viewport' content='width=device-width, initial-scale=1'>
  <style>
    #gameZone {width: 800px; height: 500px; border: 1px solid; margin: 0 auto; position: relative;}
    #gameZone img {width: 50px; position: absolute;}
  </style>
</head>
<body>
  <form name="frm">
    <input name="userid" id="id" autofocus>
    <input name="password" id="pw" type="password">
    <button name="btnLogin">로그인</button>
    
  </form>  
  <p id="result"></p>
  <p id="result2"></p>
  <hr>
  <textarea id="t1"></textarea>
  <hr>
  keyup <p id="result3"></p>
  keydown <p id="result4"></p>
  keypress <p id="result5"></p>
  change <p id="result6"></p>
  <hr>
  <div id="gameZone">
    <img id="player" src="../../htmlcss/img/네이버.jpg">
  </div>
  <script>
    let form = document.frm;
    frm.onsubmit = function() {
      event.preventDefault();
    }
    let focusTarget = document.querySelectorAll("form > *");
    focusTarget.forEach(function(item){
      item.onfocus = function() {
        document.getElementById("result").innerHTML = this.name + " focused in";
      }
      item.onblur = function() {
        document.getElementById("result2").innerHTML = this.name + " focused out"
      }
    })
    let t1 = document.getElementById("t1")
    t1.onkeyup = function() {
      document.getElementById("result3").innerText = this.value.length
      
    }
    t1.onkeydown = function() {
      document.getElementById("result4").innerText = this.value.length
    }
    t1.onkeypress = function() {
      document.getElementById("result5").innerText = this.value.length
    }
    t1.onchange = function() {
      document.getElementById("result6").innerText = this.value.length
    }

    document.getElementById("gameZone")
    let imgStyle = document.querySelector("#player").style;
    imgStyle.left = "400px"
    imgStyle.top = "250px"
    window.onkeydown = function() {
      
      console.log(event);
      // 37 left
      // 38 up
      // 39 right
      // 40 down
      switch(event.keyCode) {
        case 37 : 
          if(parseInt(imgStyle.left) > 0)
          imgStyle.left = parseInt(imgStyle.left) - 5 + "px";
          break;
        case 38 :
        if(parseInt(imgStyle.top) > 0)
          imgStyle.top = parseInt(imgStyle.top) - 5 + "px";
          break; 
        case 39 : 
           if(parseInt(imgStyle.left) < 750)
           imgStyle.left = parseInt(imgStyle.left) + 5 + "px";
          break;
        case 40 : 
         if(parseInt(imgStyle.top) < 450)
         imgStyle.top = parseInt(imgStyle.top) + 5 + "px";
          break;
      }
      
    }
  </script>
</body>
</html>

'HTML5, CSS3 > Java Script' 카테고리의 다른 글

window.onload(js)와 $(document).ready(jquery)의 차이  (0) 2024.01.17
23-02-27 JS  (0) 2023.02.27
23-02-23 JS  (0) 2023.02.23
23-02-22 JS  (0) 2023.02.22