"2018/10/14"에 해당되는 글 - 1건

Post

반응형

Javascript 정리


html과 javascript의 차이


  • html은 있는 그대로 보여주지만 javascript는 동적으로 페이지를 보여준다.
  • 아래 예는 같은 1+1을 했지만 html은 글자로써 그대로 보여주는 반면
  • javascript는 1+1의 결과값 2를 출력한다.
<!--DOCTYPE html-->
<html>
<head>
  <meta charset="utf-8">
  <title></title>
</head>
<body>
  <script>
    document.write("1+1");
    document.write(1+1);
  </script>
  <h1>1+1</h1>
</body>
</html>

javascript event


  • html에 on으로 시작하는 속성들이 있다.
  • on으로 시작하는 속성은 javascript 이벤트를 대입해야한다.
  • onclick="alert('OK')"
  • onclick 속성은 마우스 클릭(이벤트)시 OK알람창(javascript)이 뜬다.
<!--DOCTYPE html-->
<html>
<head>
  <meta charset="utf-8">
  <title></title>
</head>
<body>
  <input type="button" value="Click button" onclick="alert('OK')">
  <input type="text" onchange="alert('changed')">
  <input type="text" onkeydown="alert('key down!')">
</body>
</html>

javascript consol


  • 크롬 웹 페이지에서 오른쪽 클릭 - 검사-console 창 뜸
  • 간단한 javascript code 를  console 창에서 테스트 할 수 있다.


데이터타입-문자열과 숫자


  • 데이터 타입이 문자열인지 숫자인지에 따라 결과가 달라진다.
  • 데이터 타입 숫자 : 1+1 = 2
  • 데이터 타입 문자 : "1"+"1"="11"


프로그래밍이란?


  • javascript는 프로그래밍 언어. html 아님.
  • 프로그램이란 순서라는 의미가 있음. 만드는사람은 프로그래머.
  • html은 시간의 순서에 따라 순서대로 작동x
  • javascript는 시간의 순서에 따라 순서대로 작동.


조건문


  • == : 값이 같은지 확인
  • === : 데이터 값이 같은지 확인
  • ex.
  • 1 == "1" : true
  • 1 === "1" : false
  • true == 1 : true
  • true === 1 : false

var target = document.querySelector('body');
if(this.value === 'night')
{
    target.style.backgroundColor = 'black';
    target.style.color = 'white';
    this. value = 'day';
} else {
    target.style.backgroundColor = 'white';
    target.style.color = 'black';
    this.value = 'night';
}

function


중복된 코드가 많아지면 function 으로 grouping 해야 소스 관리가 쉽다.

  • 함수선언
<script>
function FunctionName(arg)
{
return arg;
}
</script>

  • 사용법
<input type="button" value="click" onclick="FunctionName(value)"

객체


  • 소스코드가 커지면 function 이름의 중복이 많이 나타난다.
  • function이 중복되면 나중에 선언된 function만 남고, 먼저 선언된걸 지워버린다.
  • 객체를 사용하면 객체와 관련있는 변수, 함수를 Grouping하기 때문에 function 이름 중복을 방지할 수 있다.
  • 사용법
선언
var player = { "id":"value" }
가져오기
player.id , player.value
Method 선언
var func = {
    MethodName:function(arg){
            // 내용
    },
    MethodName2:function(arg){
            // 내용
    }
}
  • Method 사용

func.MethodName1(value);



파일로 정리하기


  • js객체 정의가 각 파일마다 정의되어있다면 소스가 복잡해진다.
  • js파일을 한 파일에 넣고 정리할 수 있다.
  • js파일 참조하기
<head> 안에 <script src = "js이름.js"></script>

jquery


  • jquery 라이브러리 포함(CDN)
  • jquery 다운로드 페이지 접속 (https://jquery.com/download/)
  • 페이지에서 CDN 검색 , 구글 CDN 클릭
  • jQuery을 찾아서 아래 script를 <head>태그 안에 넣음
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

  • jquery는 javascript로 복잡하게 적은 소스를 간단하게 변경할 수 있는 좋은 라이브러리.


반응형
▲ top