window -> 브라우저 자체
-document(dom객체) ->사용시 window.document
— html 등 태그들이 들어있음
window.onlad
window.onload = function(){// 해주는 역할은 body에 있는 브라우저 태그 부분을 먼저 로드하고 생기면 자바스크립트를 통해서 동작하게//window는 생략 가능var hello=window.document.getElementById("hello1");hello.innerHTML = "안녕하세요 ineerHTML로 수정합니다";};
id를 통해 onclick 사용해보기
window.onload = function(){
btn.onclick = function(){console.log("id로 버튼 로그인 처리하기 ")}};.........
<input type="submit" value="로그인" id ="btn">
input 태그의 값을 받아서 체크해보기
//input태그에 있는 값을 가져올떄는 .value를 사용해야한다.var id = document.getElementById("id").value;var pwd = document.getElementById("pwd").value;var idcheck = document.getElementById("id-check");var pwdcheck = document.getElementById("pwd-check");if(id==""){idcheck.innerHTML="아이디를 입력해주세요";}else{idcheck.innerHTML="";}if(pwd==""){pwdcheck.innerHTML="패스워드를 입력해주세요";}else{pwdcheck.innerHTML="";}
태그 이름으로 불러오기
var div = document.getElementsByTagName("div");console.log(div);
클래스 이름으로 불러오기 (id 외에는 배열로 ->getElements 로 사용)
var className = document.getElementsByClassName("class-name");console.log(className[0].innerHTML);'
name으로 불러오기
var name = document.getElementsByName("지정된 name 값")console.log(name);
선택자를 이용한 방법
var select = document.querySelector("#id값");var select = document.querySelector(".class값");var select = document.querySelector("input[name='name값']");
-->태그를 먼저 적고 name 값 또는 input[type='text']으로 사용
child
var nodes = node.children // node는 아이디 값var input = node.createElement("input");node.appendChild(input);
//node안에 input 태그 추가
실제로는 이런식으로 태그 추가함.
noed.innerHTML+="<input type='text'><br>"
node.innerText+="fdsfsF"
이벤트
그외 이벤트 addEventListener 사용이유
(참고)https://ko.javascript.info/introduction-browser-events
onclick
프로퍼티는 단 하나밖에 없기 때문에, 복수의 이벤트 핸들러를 할당할 수 없습니다.
하나의 이벤트에 복수의 핸들러를 할당할 수 없다는 문제이죠.버튼을 클릭하면 버튼을 강조하면서 메시지를 보여주고 싶다고 해 봅시다.
두 개의 이벤트 핸들러가 필요할 겁니다. 하지만 기존 방법으로는 프로퍼티가 덮어씌워 진다는 문제가 있습니다.
웹 표준에 관여하는 개발자들은 오래전부터 이 문제를 인지하고,
addEventListener
와removeEventListener
라는 특별한 메서드를 이용해 핸들러를 관리하자는 대안을 제시했습니다.
- JQuery 와 Javascript의 차이
javascript 표준이 워낙 최근에 정해지다보니 브라우저별로 호환성이 중구난방이거든요.jQuery의 역할은 여기서 동일한 코드로 대부분의 브라우저와 버전을 지원한다는데 있습니다.
자바스크립트에서 Function
예시 (ajax에서 댓글조회 기능 할때)
특징
1. function에 사용되는 매개변수 타입을 지정하지 않아도 된다.
2.function에서는 모든 매개변수를 다 사용하지 않아도 사용가능하다.
3.매개변수에 function을 다시 구현하여 사용가능하다 예를 들어 callback이라는 매개변수이지만 실제로 getList(param , function{ }) 이렇게 구현 가능
이렇게 되면 매개변수 function{}이 callback이라는 함수로 사용된다.
//댓글처리function getList(param,callback,error){var bno =param.bno;var page =param.page || 1;$.getJSON("/replies/pages/"+bno+"/"+page+".json",function(data){if(callback){callback(data);}}).fail(function(xhr,status,err){if(error){error(err);}});}
JQUERY
홈페이지 들어가서 링크형식으로 js 파일을 다운 받아 해당 프로젝트 이클립스안에 넣는다. 그후, 코드를 적용
<script type="text/javascript" src="js/jquery-3.5.1.min.js">
다운을 받지 않고 바로 URL를 통해서 적용하는 방식은 CDN 방식이라 하고
인터넷에 JQUERY CDN 을 검색해서 해당 링크를 찾아 적용
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
jquery에서 val() /text()를 사용 ->(주의 : javascript에서는 value )
var divId = $("#div-id").text();
var inputvalue =$("#id").val();
-->$는 원래 jQuery로 사용 했으나 이마저도 줄이게 사용되었다,.divId.text("text를 넣는방법");
window.onload를 대체 하기위한 jquery 방식
$(document).ready(function(){ });
--> 자바스크립트에서 window.onload 와 동일한 jquery 방식 또한, $(function(){ }); 이렇게 사용 가능
$(“#id”) / $(“.class”) -> 클래스와 id 값을 불러와서 적용 하는법
var divClass = $(".div-class").html();$(".div-class").html("<h1>태그를 추가합니다.</h1>");
자바스크립트 기초부터 정리해보기
●자바스크립트 변수에는 let const 형식으로 선언을 할수 있다.
1. let (Variable 타입으로 rw가 가능하여 선언후에 값을 변경할수 있다.)
2. const : 읽기만 가능하여 값을 변경 못함.
let name = 'hello'
name ='hello2'const maxNumber =5 // 다음 코드에서 값을 변경하지 못한다.
●자바스크립트는 기본적으로 값을 변경 가능하고 형이 지정되어있지 않다.
primitive 타입은 값 자체가 저장 / object 타입은 ref가 저장된다.
console(‘1’+2); -> 숫자가 문자로 합쳐져서 12 로출력console(‘string literals: 1+2
; ; ; ;
= ${1+2}’); // string literals를 쓰면 띄어쓰기 특수문자 사용 가능
|| 연산자는 처음에 한번이라도 true가 나오면 거기서 멈추고 값을 반환한다.
따라서 function()1||function()2||function()3 이러한 연산을 할때는
function()1에 가장 가볍은 함수를 앞에 둔다.
( and도 앞에서 false가 나오면 거기서 멈추고 반환)
strict equality ===는 타입 형까지 비교해준다.
const ellie1 ={name : ‘ellie’};
const ellie2 ={name =’ellie’};console.log(ellie1===ellie2) -> true;
●자바스크립트에서 함수
형을 지정하지 않고 함수에 반환형이 없다
변수값 모두를 안넣어도 기본값을 설정 가능하다 .
function showMessage(message, from ='unknown){
console.log('${massage} by ${from}');
}showMessage(hi); -> 결과값 : hi by unknown
//함수 적용법const print =function(){
console.log(print);
}
print(): -> print// 함수를 이렇게 코드 가능
const print = () => console.log(print)
const add = (a,b) => a+b;(function hello() {
console.log('IIFE');
})();
// 선언함과 동시에 바로 호출 가능
●자바스크립트 for문
function arrprint(...args){
//기본 for문을 하거나
// of를 이용한 for문
for( const arg of args){
console.log(arg);
}
//자바스크립트 문법 활용
args.forEach((arg)=>console.log(arg));}arrprint('dream','config','ellie');
●scope에 대한 개념
모든 변수는 괄호안에서만 사용가능하고 밖에서 안은 가능하고,
안에있는 변수는 밖에서 불가능하다 .
●자바스크립트에서의 class
Script 6전까지는 class가 없었으며, 6이후 부터 class 선언이 가능해 졌다 .
class PersonClass {static publisher ='Dream';constructor(name){
this.name = name;
}sayName(){
console.log(this.name);
}static printPublisher(){
console.log(PersonClass.publisher);
}}let person = new PersonClass("Nic");
person.sayName();console.log(personClass.publisher);
//class안에 있는 static변수는 클래스를 이용해서만 변수를 사용가능
●상속과 다향성
class Shape {
constructor(width, height, color){
,,,
}draw(){
console.log('draw');
}getArea(){
reuturn this.with * this.heigh;
}}class Rectangle extends Shape{}class Triangle extends Shape{
draw(){
super.draw(); // Shape의 draw를 불러오고 싶을때
console.log("세모");
}getArea(){
return (this.with * this.height) /2 ;
}}const rectangle = new Rectangle(20,20,'bule');
rectangle.draw();
console.log(rectangle.getArea()) // Rectangle에서 재정의한 내용으로 출력
●자바스크립트 배열 다루기
기본
//자바스크립트 배열
const fruits = ['a','b'];//foreach
fruits.forEach((fruit, index) => console.log(fruit,index));
클래스 배열화
class Student {
constructor(name,age, enrolled, score){
this.name = name;
this.age = age;
this.enrolled = enrolled;
this.score=score;
}}const student = [
new Student('A',29, false, 45);
new Student('B',28, false, 90);
new Student('C',30, true, 45);
new Student('D',21, flase, 90);
]
find / filter 배열 다루기
// score가 90인 학생 찾기const result = students.find(function(student, index){
return student.score === 90;
console.log(student,index);});
// const result = students.find((student) => student.score === 90);// 등록되어있는 학생만
const result = student.filter((student)=>student.enrolled);
map 사용하여 배열 다루기
//학생에서 점수만 있는 배열로 만들기
// map 은 새로운 값으로 바꿀때 사용
const result = students.map((student)=> student.score);
some /every 사용하여 배열 다루기
//학생중에서 50보다 낮은게 있는지 확인
const result = students.some((student)=> student.score <50));//배열의 모든 요소가 50보다낮은지
const result = students.every((student)=> student.score <50));
reduce사용하여
// 학생들의 값 평균 구하기
//reduce는 배열을 돌면서 누적된 값을 사용할때 사용
const result = students.reduce((prev,curr)=> {
return prev + curr.score ;
},0);
// ,0을 하게 되면 처음값은 0과 index0 이 들어가고 다음은
처음 return값, index2가 들어감
console.log(result/students.length);
sort 정렬 (join은 배열을 string으로 변환 )
sort((a,b)=> a- b) : 오름차순 / sort((a,b)=> b-a) : 내림차순
sort
const result = sutdents.map((student)=> student.score).sort((a,b)=> a-b).join();
●JSON
1. Object를 json으로
함수는 Object에 포함되지 않아 json 변환시 사용할수 없다.
let json = JSON.stringify(true);const rabbit = {
name : 'tori',
color : 'white',
size : null,
birthDate : new Date(),
jump : () => { console.log('${name});
},
};
json = JSON.stringify(rabbit); // jump는 json에 포함되지 않는다.
2. json 을 Object로
const obj = JSON.parse(json);
console.log(obj);
rabbit.jump();
obj.jump() // x 쓸수 없다.rabbit.birthDate.getDate());
const obj = JSON.parse(json, (key,value) => {
return key ==='birthDate' ? new Date(value) : value;
});
console.log(obj.birthDate.getDate()); //Date함수를 이용하려면 이렇게 사용
●자바스크립트 프로미스
Promise가 왜 필요한가요?
프로미스는 주로 서버에서 받아온 데이터를 화면에 표시할 때 사용합니다.
const promise = new Promise((resolve, reject) =>{
setTimeout(()=> {resovle('ellie'); // resovle를 통해서 서버값을 전달
//reject(new Error('no network')); // 에러가 있을경우에는 reject를 사용},2000);
});// promise가 정상적으로 동작하면 .then을 수행
promise.then((value)=> {
console.log(value);}).catch(err => {
console.log(err);
});