x
Javascript 본문
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의 종류:
onchange | An HTML element has been changed |
onclick | The user clicks an HTML element |
onmouseover | The user moves the mouse over an HTML element |
onmouseout | The user moves the mouse away from an HTML element |
onkeydown | The user pushes a keyboard key |
onload | The 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
Attribute | Description |
---|---|
disabled | Specifies that the input element should be disabled |
max | Specifies the maximum value of an input element |
min | Specifies the minimum value of an input element |
pattern | Specifies the value pattern of an input element |
required | Specifies 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
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
'공부 > 웹' 카테고리의 다른 글
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 |