Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

x

Javascript 본문

공부/웹

Javascript

minkmink 2017. 1. 29. 19:29

javascript는 HTML태그의 내용을 바꿀 수 있다


getElementByID()

document.getElementById("demo").innerHTML = "Hello JavaScript";

=> demo라는 id를 가진 HTML태그 안의 내용(innerHTML)을 바꾼다


<button onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn on the light</button>

=> 버튼을 누르면 myImage라는 id를 가진 HTML태그의 src 속성을 'pic_button.gif'로 바꾼다


document.getElementById("demo").style.fontSize = "25px";

=> style은 css를 바꾼다.



<script>

javascript code는 <script>태그 안에 들어가야 한다

<script src='myscript.js'> : 외부의 myscript.js를 불러온다



JS Output

document.write() : 화면에 출력한다(테스트용)

=> HTML 파일이 모두 로드된 후 document.write()가 실행되면 기존의 모든 HTML을 삭제하고 출력한다

window.alert() : alert창을 띄운다

console.log() : 디버깅



JS Syntax

var : 변수를 선언한다 => var x, y;

나머지는 c와 유사

보통 lowercase로 시작하는 camelcase를 쓴다. ex) lastName



JS Data Types

array : var cars = ["Saab""Volvo""BMW"]; ( array도 object에 속한다)

object : var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

undefined : 초기화하지 않은 변수는 undefined 값을 가진다

null : null은 object에 해당한다

typeof : return type of variable     ex) typeof "Hello"



JS Functions

func1 : func1의 정의를 뜻함

func1() : func1함수를 호출하고 리턴함

x = func1() : func1함수를 호출하고 리턴값을 x에 저장함



JS Objects

var person = {

    firstName: "John",

    lastName : "Doe",

    id       : 5566,

    fullName : function() {

       return this.firstName + " " + this.lastName;

    }

};

멤버변수 접근 : person.firstName = person.['firstName']

메소드 접근 : person.fullName() 



JS Scope

밖에서 선언된 변수(global)는 함수 안에서도 유효하다(c와 같음)

var키워드를 사용하지 않은 변수에 값을 할당하면 자동으로 global이 된다.(함수 안에서 선언되어도 함수 밖에서도 유효하다) => 사용하지 않는 것이 바람직

window object : JS에서 global variable은 모두 window object이다

=> var carName = "volvo" --> window.carName = "volvo"

global variable은 웹브라우저나 탭이 닫힐때 삭제된다. 같은 창의 새로운 페이지에서는 유효하다



JS Events

HTML 태그 안에 삽입되어 event를 handle 할 수 있다

<some-HTML-element some-event="some JavaScript">

HTML event의 종류:

onchangeAn HTML element has been changed
onclickThe user clicks an HTML element
onmouseoverThe user moves the mouse over an HTML element
onmouseoutThe user moves the mouse away from an HTML element
onkeydownThe user pushes a keyboard key
onloadThe browser has finished loading the page


JS String

escape character('\') : 따옴표 안에 따옴표를 쓰고 싶을때 \"

== : 값을 비교 

=== : 타입과 값을 비교

JS에서 두 객체를 비교할 땐 항상 false가 반환된다(다른 객체기 때문)

str.length : str의 길이를 반환

str.indexOf("str") : 첫 번째 인덱스를 반환

str.lastIndexOf("str") : 마지막 인덱스를 반환

str.locate("str") : indexOf()와 같다

Ref => http://www.w3schools.com/js/js_string_methods.asp



JS Number

number.toString(base) : number를 base진법 string으로 변환한다



JS Math Object

Math.PI, Math.min, Math.max ...등등

Ref => http://www.w3schools.com/jsref/jsref_obj_math.asp



JS Date Object

Ref => http://www.w3schools.com/jsref/jsref_obj_date.asp



JS Array Method

toString()

join("*") 등등...



JS Array Sorting

문자열을 sort()하면 알파벳 순으로 잘 되지만, 숫자를 sort()하면 잘 안된다

sort(function(a,b){return a-b})를 이용하면 된다.



JS Loop

for(x in array){...} : array의 element를 순서대로 x에 할당한다



JS Type Conversion

.constructor property : returns the constructor function



JS Regular Expressions

/pattern/modifiers;

/w3school/i => index

/w3school/g => global matching

/w3school/m => multiline matching

RegExp Object

/e/.test("~~~") : returns true of false

/e/.exec("~~~") : returns the found text

Ref => http://www.w3schools.com/jsref/jsref_obj_regexp.asp



JS Error

try : 코드를 실행한다

catch(err) : 에러가 발생하면 에러를 err에 담고, 이하 코드를 실행한다

throw "String" : err.message 에 String을 대입한다

finally : 에러 발생 여부에 상관없이 이하 코드를 실행한다

eval("~~") : String으로 된 javascript 코드를 실행하는 함수



Strict Mode

"use strict"; : easier to write secure JS



JS JSON

JSON : JavaScript Object Notation

이름과 값 쌍으로 되어있다

객체는 {}, 배열은 []로 감싼다

JSON.parse() : JSON form의 string을 javascript object로 변환



JS Form Validation

var x = document.forms["myForm"]["fname"].value;

이런 식으로 입력값을 전달받은 다음 조건문을 이용하여 alert를 한다



HTML Form Validation

input의 attribute를 이용하여 자체적으로 validate

AttributeDescription
disabledSpecifies that the input element should be disabled
maxSpecifies the maximum value of an input element
minSpecifies the minimum value of an input element
patternSpecifies the value pattern of an input element
requiredSpecifies that the input field requires an element
type Specifies the type of an input element


JS Validation DOM

DOM.checkValidity() : HTML validation에 부합하면 true 아니면 false 리턴

DOM.validity.options : options는 validations 기준들. 기준에 부합하지 않으면 true값을 가짐

=> DOM.validity.rangeOverflow, DOM.validity.rangeUnderflow 등

DOM.validationMessage : validity가 false일때의 메시지



JS BOM(Browser Object Model)

자바스크립트가 브라우저와 '대화'할 수 있게 해준다.


window Object

모든 브라우저가 지원하며 모든 global들이 window object에 속한다

document = window.document


window screen

그냥 screen으로 쓰인다

Ref => http://www.w3schools.com/js/js_window_screen.asp


window location

그냥 location으로 쓰인다

  • window.location.href : the href (URL) of the current page
  • window.location.hostname : the domain name of the web host
  • window.location.pathname : the path and filename of the current page
  • window.location.protocol : the web protocol used (http: or https:)
  • window.location.assign : loads a new document


window history
그냥 history으로 쓰인다
history.back() : 뒤로가기
history.forward() : 앞으로가기


window navigator : 브라우저에 대한 정보를 포함한다


JS popup boxes
window.alert("message") : message창을 띄운다
window.confirm("message") : message창을 띄우고 확인버튼 누르면 true, 취소버튼 누르면 false
window.prompt("message", "default input") : message창을 띄우고 입력을 받는다. 입력된 값을 리턴


JS timing events
myVar = window.setTimeout(function, 3000) : function을 3초 뒤에 실행
window.clearTimeout(myVar) : Timeout을 해제한다
myVar = window.setInterval(function, 3000) : function을 3초 간격으로 실행
window.clearInterval(myVar) : Interval을 해제한다


JS Cookie
document.cookie = "name = value"; 이외에 만료기간 등을 설정할 수 있다
document.cookie는 모든 쿠키를 리턴한다(cookie1 = val1; cookie2 = val2; ....)
쿠키 set, get, check 함수 => http://www.w3schools.com/js/js_cookies.asp



HTML DOM(Document Object Model)

The HTML DOM is a standard object model and programming interface for HTML. It defines:

  • The HTML elements as objects
  • The properties of all HTML elements
  • The methods to access all HTML elements
  • The events for all HTML elements
최상위 object는 document이다

document.getElementById("demo").innerHTML
getElementById : method, HTML element에 access한다
innerHTML : property, HTML element의 속성


DOM Element
document.getElementById("intro");
document.getElementsByTagName("p");
document.getElementsByClassName("intro");
document.querySelectorAll("p.intro");
document.forms
document.body 등등


DOM Eventlistener
element.addEventListener("click"function(){ alert("Hello World!"); });
함수 부분에는 myFunction 처럼 괄호를 붙이지 않은 함수 자체를 인자로 주거나
인자를 넘겨주고 싶을 땐 function(){myFunction(v1, v2);} 형태로 준다
Bubbling & Capturing
Bubbling : 안쪽 태그가 먼저 반응
Capturing : 바깥쪽 태그가 먼저 반응
element.removeEventListener("mousemove", myFunction); : eventlistener를 삭제한다


DOM node

document - head(1st child)



 - body(2nd child)  - p(1st child) - "hello world"(1st child)

































'공부 > ' 카테고리의 다른 글

Webhacking.kr 16 keyCode  (0) 2017.01.30
webhacking.kr 26 url encoding  (0) 2017.01.28
Webhacking.kr 24 쿠키값 변조  (0) 2017.01.28
HTML  (0) 2017.01.27
XSS (Cross site scripting)  (0) 2017.01.27
Comments