본문 바로가기

대학교 2학년 1학기/웹프로그래밍

자바스크립트 기본 문법 정리

728x90

문서 객체 사용

script 태그 안에 이벤트를 활용 window.onload = function () { };

 

문서 객체 선택

document.getElementByID(아이디): 아이디로 1 선택

document.querySelector(선택자): 선택자로 1 선택

document.querySelectorAll(선택자): 선택자로 여러 개 선택

 

글자 조작

textContent: 순수 텍스트 형식

innerText: 렌더링 한 텍스트 형식

innerHTML: HTML 태그를 함께 가져옴

ex)

var output = '<p> <b>'+ 1 +' </b> </p>';

document.getElementById('innerHTML').innerHTML = output; // 1 출력

document.getElementById('innerText').innerText = output; // <p> <b>1</b> </p> 출력

 

스타일 조작

- ‘-’ (하이픈)를 식별자에 사용하지 못하므로 ‘-’로 연결된 단어의 첫 글자를 대문자로 변경

ex)

var header1 = docment.getElementById('header');

header1.style.backgroundColor = 'red';

 

속성 조작

- “문서객체.속성이름”으로 속성을 읽거나 설정 가능함

ex)

var image = document.getElementById('image’);

image.src = 'http://placehold.it/300x200’;

- 웹 표준에 지정되지 않은 속성은 setAttribute로 지정, getAttribute로 추출

ex)

document.body.setAttribute('data-custom', 'value’);

var dataCustom = document.body.getAttribute('data-custom’);

console.log(dataCustom); // value 출력

 

동적 문서 객체 조작

ex) setInterval(function () { }, 시간);

 

이벤트

이벤트 연결

• 인라인 이벤트 모델: 태그 내부에 자바스크립트 코드를 넣어 이벤트 연결

ex) <button onclick="alert('click')">버튼</button>

• 고전 이벤트 (기본 이벤트) 모델: 문서 객체의 이벤트 속성을 사용하여 이벤트 연결

ex)

window.onload = function () {

     var button = document.getElementById('button');

     button.onclick = function () {alert('click');};

};

• 표준 이벤트 모델: 문서 객체의 addEventListener 메서드를 사용하여 이벤트 연결

window.onload = function () {

     var button = document.getElementById('button');

     // 이벤트를 연결

     button.addEventListener('click’,

     function(){

          alert("표준 이벤트 모델");

     });

};

 

이벤트 제거

- return false;

 

 

 

 

 

728x90

'대학교 2학년 1학기 > 웹프로그래밍' 카테고리의 다른 글

jQuery 라이브러리 간단 정리  (0) 2022.06.23
HTML, CSS 간단 요약  (0) 2022.05.20
HTML5 정리  (0) 2022.04.04