728x90
반응형
728x90
반응형

수업의 목적

자바스크립트는 야간모드와 주간모드를 버튼을 통해 만들 수 있습니다. 즉 사용자와 상호작용 한다는 의미

1. 자바스크립트는 사용자와 상호작용하는 언어

2. 웹 브라우저는 한번 출력하면 바뀔 수 없지만 바디 태그 내 디자인을 바꿀 수 있습니다.

자바스크립트는 HTML을 제어하는 언어(동적으로 만들어주는 특성을 가짐)



HTML JavaScript의 만남 (script 태그)

HTML은 정적 JavaScript는 동적

<h1>JavaScript</h1>

<script>

  document.write(1+1); // 2

</script>

<h1>html</h1>

1+1 <!-- 1+1의 문자열을 출력 -->

 

HTML JavaScript의 만남 (이벤트)

웹 브라우저에서 일어나는 일(사건)을 이벤트라고 합니다.

웹 브라우저에서 일어나는 이벤트의 예

<input type="button" value="hi" onclick="alert('hi')">

<input type="text" onchange="alert('changed')">

<input type="text" onkeydown="alert('key down!')">




 

HTML JavaScript의 만남(콘솔)

콘솔을 통해 웹 페이지를 대상으로 자바스크립트가 실행됩니다.

 

데이터 타입 문자열과 숫자

데이터 타입은 자료형

‘hello world’.indexOf(‘o’) //4

‘hello world’.toUpperCase() // HELLO WORLD

 

변수와 대입 연산자

좌항과 우항을 결합해 우항의 결과를 만든다

name의 개수가 1억 개일 경우 변경하기 쉽지 않습니다. 변수를 지정해 값을 쉽게 변경할 수 있습니다.

 

웹 브라우저 제어

자바스크립트를 이용해 제어하고자 하는 태그를 선택하는 방법

 

CSS기초(style 속성·태그, 선택자)

<h1 style=”backgroudcolor:red;color:blue”>JavaScript</h1>

<div>JavaScript</div> <span style=”font-weight:bold;”>JavaScirpt</span> 전체를 쓰는지 안 쓰는지의 차이

반은 클래스 학생들을 그룹핑, id는 학번의 개념 중복될 수 없습니다.

<h1><a href="index.html">WEB</a></h1>

  <h2 style="background-color:coral;color:powderblue;">JavaScript</h2>

  <p>

    <span id="first" class="js">JavaScript</span> (/ˈdʒɑːvəˌskrɪpt/[6]), often abbreviated as JS, is a high-level, dynamic, weakly typed, prototype-based, multi-paradigm, and interpreted programming language. Alongside <span>HTML</span> and <span>CSS</span>, <span class="js">JavaScript</span> is one of the three core technologies of World Wide Web content production. It is used to make webpages interactive and provide online programs, including video games. The majority of websites employ it, and all modern web browsers support it without the need for plug-ins by means of a built-in <span class="js">JavaScript</span> engine. Each of the many <span class="js">JavaScript</span> engines represent a different implementation of <span class="js">JavaScript</span>, all based on the ECMAScript specification, with some engines not supporting the spec fully, and with many engines supporting additional features beyond ECMA.

</p>


출처 : 생활코딩 강의

728x90
반응형
728x90
반응형

이벤트타입

이벤트 타입이라는 것은 이벤트의 종류

 -(submit, change, blur, focus)

*submit : 폼의 정보를 서버로 전송하는 명령

*change : 폼 컨트롤의 값이 변경되었을 때 사용

*blur, focus : focus는 엘리먼트에 포커스가 생겼을 때, blur은 포커스가 사라졌을 때 발생하는 이벤트



 -문서 로딩

console.log(t); // null 을 출력, 스크립트 호출 시 id‘target’이 존재하지 않기 때문

<head>

    <script>

        window.addEventListener('load', function(){ //

            var t = document.getElementById('target');

            console.log(t); // p#target

        })

    </script>

</head>

<body>

    <p id="target">Hello</p>

</body>

load 이벤트는 문서내의 모든 리소스(이미지, 스크립트)의 다운로드가 끝난 후에 실행되기 때문에 앱의 구동이 지연되는 부작용이 초래할 수 있습니다.

DOMContentLoaded는 문서에서 스크립트 작업을 할 수 있을 때 실행되기 때문에 이미지 다운로드를 기다릴 필요가 없습니다.

실제 라이브러리 사용으로 내부적으로 알아서 채택합니다. 이벤트 타입 때문에 고민하는 경우가 없습니다. 하지만 둘의 차이는 아는 것이 중요합니다.

 -마우스

Click : 클릭했을 때 발생하는 이벤트 Dblclick : 더블클릭을 했을 때 발생하는 이벤트

Mousedown : 마우스를 누를 때 발생 Mouseup : 마우스버튼을 땔 때 발생

Mousemove : 마우스를 움직일 때 Mouseover : 마우스가 엘리먼트에 진입할 때 발생

Mouseout : 마우스가 엘리먼트에서 빠져나갈 때 발생 Contextmenu : 컨텍스트 메뉴가 실행될 때 발생

키보드 조합

event.shiftKey, event.altKey, event.ctrlKey

마우스 포인터 위치 : 이벤트 객체의 clientX clientY를 사용

jQuery이벤트(jQuery none jQuery의 비교)





jQuery를 사용하지 않았을 경우의 코드 분량에 차이가 있습니다.

또한, jQuery는 크로스 브라우징을 알아서 처리해주고, 이벤트를 보다 적은 코드로 구현할 수 있도록 합니다. 이러한 이유로 jQuery와 같은 라이브러리를 사용합니다.

-on API 사용법(On jQuery에서 가장 중요한 API)

selector 인자

<ul>

    <li><a href="#">HTML</a></li>

    <li><a href="#">CSS</a></li>

    <li><a href="#">JavaScript</a></li>

</ul>

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>

<script>

    $('ul').on('click','a, li', function(event){

        console.log(this.tagName); // A LI

    })

</script>

두 번째 인자에 ‘a li’ 태그를 필터링 했기 때문에 ul태그에 대한 이벤트가 발생하는 것이 아님

Late binding(존재하지 않는 엘리먼트에도 이벤트를 등록할 수 있는 기능)

다중 바인딩(하나의 엘리먼트에 여러개의 이벤트 타입을 동시에 등록하는 방법)

이벤트 제거(off를 사용)

<input type="text" id="target"></textarea>

<input id="remove"  type="button" value="remove" />

<p id="status"></p>

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>

<script>

  var handler = function(e){

    $('#status').text(e.type+Math.random());

  };

  $('#target').on('focus blur', handler) // focus이벤트만 삭제

  $(‘#target’).on(‘focus’, function(e){

  alert(1);

)

  $('#remove').on('click' , function(e){

    $('#target').off('focus', handler);

  })

</script>

 

네트워크통신

자바스크립트를 이용해서 웹브라우저의 통신 기능

Ajax(페이지 리로드 없이 웹페이지의 내용을 변경할 수 있는 것)

Asynchronous JavaScript And XML : 비동기적 자바스크립트와 XML

비동기적으로 자바스크립트를 이용해 서버와 통신하는 방법

if(통신완료 && 통신성공) = if(xhr.readyState && xhr.status)

POST방식

JSON(서버와 클라이언트 간의 데이터를 주고 받는 형식)

JavaScript Object Notation : 자바스크립트에서 객체를 만들 때 사용하는 표현식

JSON API

*JSON.parse() : 인자로 전달된 문자열을 자바스크립트의 데이터로 변환

*JSON.stringify() : 인자로 전달된 자바스크립트의 데이터를 문자열로 변환

Ajax JSON

Json은 모든 언어에서 객체와 배열로 사용할 수 있는 특징이 있음

JSON의 적용

var tzs = JSON.parse(_tzs); //자바스크립트의 데이터로 변환

jQueryAjax

브라우저간의 차이(크로스 브라우징)jQuery가 알아서 해결합니다.

 

http://api.jquery.com/category/ajax/

data : 서버로 데이터를 전송할 때 이 옵션을 사용

dataType : 서버 측에서 전송한 데이터를 어떤 형식의 데이터로 해석할 것인가를 지정, 값으로 올 수 있는 것은 xml, json, script, html으로 형식을 지정하지 않으면 jQuery가 알아서 판단합니다.

success : 성공했을 때 호출할 콜백을 지정, Function( PlainObject data, String textStatus, jqXHR jqXHR )

type : 데이터를 전송하는 방법을 지정, get, post를 사용

serialize() : select, texarea, text, checkbox 등의 값을 리턴

JSON처리방식



출처 : 생활코딩 강의

728x90
반응형
728x90
반응형

이벤트(사건을 의미)

브라우저에서 사건이란 사용자가 마우스 버튼을 클릭했을 때, 스크롤 했을 때, 필디의 내용을 바꿨을 때 등을 의미

event targert : 이벤트가 발생하는 대상

event type : onclick, onchange ‘의 의미

event handler : 이벤트가 발생했을 때 동작하는 코드

등록방법

 -inline

태그 안에 이벤트가 속성으로 들어가는 방식, this는 함수가 속한 객체를 의미

<!--자기 자신을 참조하는 불편한 방법-->

<input type="button" id="target" onclick="alert('Hello world, '+document.getElementById('target').value);" value="button" />

<!--this를 통해서 간편하게 참조할 수 있다, this input엘리먼트를 의미-->

<input type="button" onclick="alert('Hello world, '+this.value);" value="button" />

편리하지만 태그에 직접 기술됨, html이 기본적으로 추구하는 방향은 css script코드를 따로 분류하는 형태, 복잡한 코드를 넣을 수 없음

 -프로퍼티리스너

이벤트 대상에 해당하는 객체의 프로퍼티로 이벤트를 등록하는 방식

   




   

-addEventListener()

 

<input type="button" id="target" value="button" />

<script>

    var t = document.getElementById('target');

    t.addEventListener('click', function(event){

        alert(1);

    });

    t.addEventListener('click', function(event){

        alert(2);

    });

</script>

프로퍼티 이벤트로 사용시 1개의 핸들러만 사용가능하지만 add이벤트리스너는 추가합니다.

이벤트 객체를 이용하면 복수의 엘리먼트에 하나의 리스너를 등록해서 재사용할 수 있습니다.

이벤트 전파(버블링 bubbling과 캡처링 capturing)

캡처링

버블링, 이벤트 전파에 주로 사용

stopPropagation()

 

기본동작의 취소

*텍스트 필드에 포커스를 준 상태에서 키보드를 입력하면 텍스트가 입력된다.

*폼에서 submit 버튼을 누르면 데이터가 전송된다.

*a 태그를 클릭하면 href 속성의 URL로 이동한다.

기본적인 동작을 기본 이벤트라고 하는데 사용자가 만든 이벤트를 이용해 동작을 취소할 수 있습니다.

 -inline방식

 

opentutorials

   

 

 -property방식


 -addEventListener방식



출처 : 생활코딩 강의

 

728x90
반응형
728x90
반응형

Document 객체

 

 



TEXT객체

 

생활코딩

: p태그는 텍스트 객체

Hello world

Hello world

 


API

텍스트 노드는 DOM에서 실질적인 데이터가 저장되는 객체

 
  • html
  • css
  • JavaScript
 


 

조작API

<!DOCTYPE html>

<html>

<head>

    <style>

    #target{

        font-size:77px;

        font-family: georgia;

        border-bottom:1px solid black;

        padding-bottom:10px;

    }

    p{ margin:5px }

    </style>

</head>

<body>

<p id="target">Cording everybody!</p>

<p> data : <input type="text" id="datasource" value="JavaScript" /></p>

<p> start :<input type="text" id="start" value="5" /></p>

<p> end : <input type="text" id="end" value="5" /></p>

<p><input type="button" value="appendData(data)" onclick="callAppendData()" />

<input type="button" value="deleteData(start,end)" onclick="callDeleteData()" />

<input type="button" value="insertData(start,data)" onclick="callInsertData()" />

<input type="button" value="replaceData(start,end,data)" onclick="callReplaceData()" />

<input type="button" value="substringData(start,end)" onclick="callSubstringData()" /></p>


</body>

</html>

문서의 기하하적 특성

문서의 엘리먼트의 크기, 위치, 스크롤 등을 제어하는 방법

<style>

    body{

        padding:0;

        margin:0;

    }

    div{

        border:50px solid #1065e6;

        padding:50px;

        margin:50px;

    }

    #target{

        width:100px;

        height:100px;

    }

</style>

<div>

    <div id="target">

        Coding

    </div>

</div>

 


 


문서 viewport

스크롤

<style>

    body{

        padding:0;

        margin:0;

    }

    div{

        border:50px solid #1065e6;

        padding:50px;

        margin:50px;

    }

    #target{

        width:100px;

        height:2000px;

    }

</style>

<input type="button" id="scrollBtn" value="scroll(0, 1000)">

<script>

    document.getElementById('scrollBtn').addEventListener('click', function(){

        window.scrollTo(0, 1000); // x, y 좌표

    })

</script>

<div>

    <div id="target">

        Coding

    </div>

</div>

스크린 크기


스크린 크기의 정보가 중요한 이유 :

웹 페이지의 폭을 사용자의 정보를 수집해 의사결정에 도움이 됩니다.



출처 : 생활코딩 강의

728x90
반응형
728x90
반응형

Element 객체

Element 객체는 엘리먼트를 추상화한 객체

DOM은 마크업언어를 제어하기 위한 표준

 


 -식별자 API

<script>

console.log(document.getElementById('active').tagName)// LI
 var active = document.getElementById('active');
console.log(active.id); // active
var active = document.getElementById('active');
// class 값을 변경할 때는 프로퍼티의 이름으로 className을 사용
active.className = "important current";
console.log(active.className); // important current
active.className += " readed" // 클래스를 추가할 때는 아래와 같이 문자열의 더한다.
var active = document.getElementById(‘active’);
for(var i=0; i<active.classList.length; i++){
        console.log(i, active.classList[i]);
}
active.classList.add('marked'); // 추가
active.classList.remove('important'); // 제거
active.classList.toggle('current'); // 토글
</script>


 -조회 API

  <script>

    var list = document.getElementsByClassName('marked');

    console.group('document');

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

        console.log(list[i].textContent); // html, dom, bom

    }

    console.groupEnd();

    

    console.group('active');

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

    var list = active.getElementsByClassName('marked');

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

        console.log(list[i].textContent); // dom, bom

    }

    console.groupEnd();

</script>

  

 -속성 API

<a id="target" href="http://opentutorials.org">opentutorials</a>

<script>

var t = document.getElementById('target');

console.log(t.setAttribute(‘href’, ‘http://opentutorials.org/course/1’);

console.log(t.getAttribute('href')); //http://opentutorials.org

t.setAttribute('title', 'opentutorials.org'); // title 속성의 값을 설정한다.

console.log(t.hasAttribute('title')); // true, title 속성의 존재여부를 확인한다.

t.removeAttribute('title'); // title 속성을 제거한다.

console.log(t.hasAttribute('title')); // false, title 속성의 존재여부를 확인한다.

</script>

속성과 프로퍼티

<p id="target">

    Hello world

</p>

<script>

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

    target.setAttribute('class', 'important');  // attribute 방식

    target.className = 'important'; //// property 방식

</script>

속성과 프로퍼티 둘의 차이점

<a id="target" href="./demo1.html">ot</a>

<script>

//현재 웹페이지가 http://localhost/webjs/Element/attribute_api/demo3.html 일 때

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

console.log('target.href', target.href); // http://localhost/webjs/Element/attribute_api/demo1.html

console.log('target.getAttribute("href")', target.getAttribute("href")); // ./demo1.html

</script>

 -jQuery 속성 제어 API

<a id="target" href="http://opentutorials.org">opentutorials</a>

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>

<script>

var t = $('#target');

console.log(t.attr('href')); //http://opentutorials.org

t.attr('title', 'opentutorials.org'); // title 속성의 값을 설정한다.

t.removeAttr('title'); // title 속성을 제거한다.

</script>

jquery에서 attribute property

<a id="t1" href="./demo.html">opentutorials</a>

<input id="t2" type="checkbox" checked="checked" />

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>

<script>

// 현재 문서의 URL이 아래와 같다고 했을 때,

// http://localhost/jQuery_attribute_api/demo2.html

var t1 = $('#t1');

console.log(t1.attr('href')); // ./demo.html

console.log(t1.prop('href')); // http://localhost/jQuery_attribute_api/demo.html

 

var t2 = $('#t2');

console.log(t2.attr('checked')); // checked

console.log(t2.prop('checked')); // true

</script>

Attr attribute, prop property 방식

 -jQuery 조회 범위 제한

<ul>

    <li class="marked">html</li>

    <li>css</li>

    <li id="active">JavaScript

        <ul>

            <li>JavaScript Core</li>

            <li class="marked">DOM</li>

            <li class="marked">BOM</li>

        </ul>

    </li>

</ul>

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>

<script>

    //$( ".marked", "#active").css( "background-color", "red" );

    //$( "#active .marked").css( "background-color", "red" );

    $( "#active").find('.marked').css( "background-color", "red" );

</script>

find를 너무 복잡하게 사용하면 코드를 유지보수하기 어렵습니다.

Node객체

시조는 최상위의 조상을 의미

node객체는 최상위 객체를 의미, 모든 객체는 node객체를 상속받음

 -Node 관계 API

 

<body id="start">

<ul>

    <li><a href="./532">html</a></li>

    <li><a href="./533">css</a></li>

    <li><a href="./534">JavaScript</a>

        <ul>

            <li><a href="./535">JavaScript Core</a></li>

            <li><a href="./536">DOM</a></li>

            <li><a href="./537">BOM</a></li>

        </ul>

    </li>

</ul>

<script>

var s = document.getElementById('start');

console.log(1, s.firstChild); // #text

var ul = s.firstChild.nextSibling

console.log(2, ul); // ul

console.log(3, ul.nextSibling); // #text, 다음 형제 노드

console.log(4, ul.nextSibling.nextSibling); // script

console.log(5, ul.childNodes); //text, li, text, li, text, li, text

console.log(6, ul.childNodes[1]); // li(html), 자식노드들을 유사배열에 담아서 리턴

console.log(7, ul.parentNode); // body

</script>

</body>

 -노드 종류 API

Node.nodeType // node의 타입을 의미

Node.nodeName // node의 이름 (태그명을 의미)

재귀함수 : 함수가 지가 자신을 호출하는 것

<!DOCTYPE html>

<html>

<body id="start">

<ul>

    <li><a href="./532">html</a></li>

    <li><a href="./533">css</a></li>

    <li><a href="./534">JavaScript</a>

        <ul>

            <li><a href="./535">JavaScript Core</a></li>

            <li><a href="./536">DOM</a></li>

            <li><a href="./537">BOM</a></li>

        </ul>

    </li>

</ul>

<script>

function traverse(target, callback){

    if(target.nodeType === 1){ // 1==Node.ELEMENT_NODE

        //if(target.nodeName === 'A')

        callback(target);

        var c = target.childNodes; // 자식 노드들을 유사배열에 담아서 리턴

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

            traverse(c[i], callback);      

        }  

    }

}

traverse(document.getElementById('start'), function(elem){

    console.log(elem);

});

</script>

</body>

</html>

 -노드 변경 API

   

appendChild(child) // 노드의 마지막 자식으로 주어진 엘리먼트 추가

insertBefore(newElement, referenceElement) // appendChild와 동작방법은 같으나 두번째 인자로 엘리먼트를 전달 했을 때 이것 앞에 엘리먼트가 추가

removeChild(child) // 노드 제거

replaceChild(newChild, oldChild) // 노드 바꾸기

 -jQuery 노드 변경 API

.jQuery에서 노드를 제어하는 기능은 주로 Manipulation 카테고리에 속해 있음

<div class="target">

    content1

</div>

<div class="target">

    content2

</div>

 

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>

<script>

    $('.target').before('<div>before</div>');

    $('.target').after('<div>after</div>');

    $('.target').prepend('<div>prepend</div>'); // 이전 추가

    $('.target').append('<div>append</div>'); // 이후 추가

</script>

remove는 선택된 엘리먼트를 제거하는 것이고 empty는 선택된 엘리먼트의 텍스트 노드를 제거하는 것

<div class="target" id="target1">

    target 1

</div>

<div class="target" id="target2">

    target 2

</div>

 

<input type="button" value="remove target 1" id="btn1" />

<input type="button" value="empty target 2" id="btn2" />

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>

<script>

    $('#btn1').click(function(){

        $('#target1').remove();

    })

    $('#btn2').click(function(){

        $('#target2').empty();

    })

</script>

교체

 

클론

이동

 -문자열 노드 제어

   innerHTML : 문자열로 자식 노드를 만들 수 있는 기능을 제공

   outerHTML : 선택한 엘리먼트를 포함해서 처리

   innerTEXT, innerTEXT : innerHtml, outerHTML과 다르게 이 API들은 값을 읽을 때는 HTML 코드를 제외한 문자열을 리턴하고, 값을 변경할 때는 HTML의 코드를 그대로 추가

   insertAdjacentHTML : 좀 더 정교하게 문자열을 이용해서 노드를 변경하고 싶을 때 사용

   

 



출처 : 생활코딩 강의

728x90
반응형
728x90
반응형

DOM

Document Object Model로 웹 페이지를 자바스크립트로 제어하기 위한 객체 모델을 의미합니다. Window 객체의 document 프로퍼티를 통해서 사용할 수 있습니다. Window 객체가 창을 의미한다면 Document 객체는 윈도우에 로드된 문서를 의미한다고 할 수 있습니다.

제어 대상을 찾기

브라우저가 만든 객체를 찾는 것

*document.getElementsByTagName : 태그의 이름이 li인 객체를 리턴합니다.

ul태그 내에 있는 li에 해당하는 객체를 찾으려면 즉 조회의 대상을 좁히려면

var ul = = document.getElementsByTagName('ul’)[0];

var lis = ul.getElementsByTagName('li');

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

        lis[i].style.color='red';  

    }

*document.getElementsByClassName : className‘active’ 엘리먼트를 조회

var lis = document.getElementsByClassName('active');

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

        lis[i].style.color='red';  

    }

*document.getElementById : 하나의 결과만을 조회, id‘active’ 엘리먼트를 조회

var li = document.getElementById('active');

li.style.color='red';

문서에서 id는 유일무이한 식별자 값이기 때문에 하나의 값이 됩니다.

*document.querySelector : 선택자를 인자로 받아 해당하는 엘리먼트를 리턴

var li = document.querySelector('li');

li.style.color='red';

var li = document.querySelector('.active');

li.style.color='blue';

jQuery(자바스크립트 라이브러리)

DOM을 내부에 감추고 보다 쉽게 웹 페이지를 조작할 수 있도록 돕는 도구

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script> <!--jquery사용법, http://와 같게 동작 -->

<script src=”../lib/jQuery/jquery-1.11.0.min.js”> <!--같은 방법-->

<script>

    jQuery( document ).ready(function( $ ) {

      $('body').prepend('<h1>Hello world</h1>'); // prepend() : 추가하는 메소드

    });

</script>


제어 대상을 찾기(jQuery)

jQuery의 기본 문법은 단순하고 강력합니다.

$() jquery function . 은 엘리먼트를 재어하는 다양한 메소드

Jquery 객체 : jquery function함수를 통해 리턴된 값

Jquery dom의 차이

코딩의 길이가 다름, 코드작성이 수월함, 빠르게 처리 가능

클래스명을 줄 때 .을 쓴다.

Id값은 #을 사용, 코드의 중복 사용을 없앨 수 있음(Chaining)

HTMLElement

 
  • HTML
  • CSS
  • JavaScript
 

document.getElementById : 리턴 데이터 타입은 HTMLLIELement, 1개만 리턴

document.getElementsByTagName : 리턴 데이터 타입은 HTMLCollection, 복수개를 리턴

 

링크는 href속성이 있어 href는 주소를 나타냄

Input의 경우 type, value의 속성이 있음

각각의 성격과 쓰임과 스펙에 따라 의미가 다름

 
opentutorials
  • HTML
  • CSS
  • JavaScript
 

 

모든 엘리먼트는 HTMLElement의 자식입니다. 따라서 HTMLElement의 프로퍼티를 똑같이 가지고 있습니다. 동시에 엘리먼트의 성격에 따라서 자신만의 프로퍼티를 가지고 있는데 이것은 엘리먼트의 성격에 따라서 달라집니다. HTMLElement Element의 자식이고 Element Node의 자식입니다. Node Object의 자식입니다. 이러한 관계를 DOM Tree라고 합니다.

HTMLCollection

리턴 결과가 복수인 경우에 사용하게 되는 객체

 

jQuery 객체

var li = $(‘li’); jquery function, li jquery object

li.css(‘text-decoration’, ‘underline’); //암시적 반복

 

jquery 객체 조회하기

 


 

Map()함수를 사용해 조회 결과 이용

 


 



출처 : 생활코딩 강의

728x90
반응형
728x90
반응형

BOM(Browser Object Model)

웹 브라우저의 창이나 프레임을 추상화해서 프로그래밍적으로 제어할 수 있도록 제공하는 수단, Window 객체의 프로퍼티와 메소드의 사용법을 배우는 것

전역객체 Window

alert('Hello world'); //window를 생략한 것과 같은 효과

window.alert('Hello world');

bom, dom, jsCore 모두 Window에 소속되어 있는 객체

웹브라우저 자바스크립트에서 Window 객체는 ECMAScript의 전역객체이면서 동시에 웹브라우저의 창이나 프레임을 제어하는 역할을 합니다.

 

사용자와 커뮤니케이션 하기

alert 경고창 :  사용자에게 정보를 제공하거나 디버깅의 용도로 사용

confirm : 확인을 누르면 true, 취소를 누르면 false값을 리턴

prompt : 사용자가 입력한 값을 받아 js가 얻을 수 있는 기능


Location 객체

location객체는 문서의 주소와 관련된 객체로 window 객체의 프로퍼티입니다.

객체를 이용해 문서의 URL을 변경할 수 있고, 문서의 위치와 관련해 다양한 정보를 얻을 수 있습니다.

현재 윈도우의 URL 알아내기 : console.log(location.toString(), location.href);

http : 웹 페이지를 웹 서버와 클라이언트가 정보를 주고 받기 위한 통신 규약

host : 컴퓨터를 식별하는 것

port : 컴퓨터에 돌아가는 서버, 소프트웨어들 식별하는 것

location.protocol : http , location.host : opentutorials.org

location.port : 80, location.pathname : /module/904/6634

location.search : 물음표 뒤에 따라오는 정보, location.hash : #뒤에 정보

location객체는 URL변경과 reload의 기능도 합니다.

location.href = ‘http://www.naver.com’;

location = ‘animal-park.tistory.com’;

location.reload();

Navigator 객체

Navigator객체 : 브라우저의 정보를 제공하는 객체

크로스 브라우징(Cross Browsing) :

ie, ff, chrome, safari, opera 각각의 브라우저 동작 방법은 W3C(dom), ECMA(js) 국제 표준화 기구에서 정의한 스펙에 따라 브라우저를 만드는 것

넷스케이프              Internet Explorer

addEventListener      attachEvent

개발자의 고충을 해결하기 위해 등장한 것이 웹 표준

표준에 정의된 스펙을 따르며 효율적으로 성능의 면으로 경쟁을 하게 됩니다.

 

console.dir(navigator); // navigator객체 프로퍼티의 리스트를 알 수 있음

console.log(appName); // 웹브라우저의 이름으로 IE Microsoft Internet Explorer, 파이어폭스, 크롬등은 Nescape로 표시

console.log(appVersion); // 브라우저의 버전을 의미

console.log(platform); // 브라우저가 동작하고 있는 운영체제에 대한 정보

 

창 제어

window.open : 새창을 만드는 메소드

window.close : 새창을 닫는 메소드

팝업 차단

같은 도메인의 사이트라면 원격에 다른 웹 페이지를 제어하는 것을 허용합니다.

도메인이 다르다면 서비스에 접근해 악의적인 일을 할 수 있기 때문에 제어를 허용하지 않습니다.

팝업을 기본적으로 차단하고 명시적으로 허용할 때 사이트가 열리도록 함

스크립트 태그 안의 팝업은 차단되지만 window.open 시 팝업은 차단되지 않습니다.


출처 : 생활코딩 강의

728x90
반응형
728x90
반응형

HTML CSS JavaScript(웹 페이지를 제어하는 역할)

HTML에서 JavaScript로드하기

Inline 방식은 태그에 직접 자바스크립트를 직접 기술하는 방식입니다.

장점은 연관된 스크립트가 분명하게 드러난다는 점입니다. 하지만 정보와 제어가 같이 있기 때문에 정보로서 가치가 떨어집니다.

<input type="button" onclick="alert('Hello world')" value="Hello world" />

<script>태그 이용

<input type="button" id="hw" value="Hello world" />

<script type="text/javascript">

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

    hw.addEventListener('click', function(){

        alert('Hello world');

    })

</script>

html코드 안에 자바스크립트가 존재하지 않습니다. 또한, 자바스크립트 유지보수하기에 바람직합니다.

외부 파일로 분리

정보와 제어의 결합도를 낯추며 유지보수의 편의성이 높아집니다.

<script src="./script2.js"></script>

script2.js  파일 내 코드

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

hw.addEventListener('click', function(){

    alert('Hello world');

})

Script파일의 위치

  

head 태그에 위치시킬 수 있지만 이 경우는 오류가 발생할 수 있습니다.

Id hw의 존재를 해석하기 전의 상태에서 조회를 하고 있기 때문에 null의 상태가 됩니다. 존재하지 않는 객체를 호출한 상태이기 때문에 오류가 발생합니다.

window.onload = function(){

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

    hw.addEventListener('click', function(){

        alert('Hello world');

    })

} //윈도우 객체 onload를 호출하도록 약속, 태그가 화면이 등장한 이후 스크립트 //코드가 실행되기 때문에 오류를 없앨 수 있습니다.

script 파일은 head 태그 보다 페이지의 하단에 위치시키는 것이 더 좋은 방법입니다.


Object Model

객체화란 무엇인가?



테두리와 같은 역할을 합니다.

각각의 태그마다 객체를 만들어 준비를 해놓은 상태, 태그에 해당하는 객체를 찾아 메소드를 호출하거나 프로퍼티를 가져오는 것

객체화 = 객체 제어 방법

var imgs = document.getElementsByTagName(‘img’);

imgs[0].style.width=’300px’;

 

JavaScript Core, BOM DOM(윈도우 객체의 프로퍼티)

window : 전역객체

JavaScript Core : JavaScript 언어 자체에 정의되어 있는 객체들

BOM(Browser Object Model) : 웹페이지의 내용을 제외한 브라우저의 각종 요소들을 객체화시킨 것

DOM(Document Object Model) : 웹페이지의 내용을 제어


출처 : 생활코딩 강의

728x90
반응형
728x90
반응형

+ Recent posts