JavaScript ES5 | JeongKeepsCalm

JavaScript ES5

비동기통신

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$.get('https://codingapple1.github.io/hello.txt')
  .done(function(res){
  console.log(res);
})
  .fail(function(error){
  console.log('fail');
}) // done, fail -> then, catch

// 서버에서 데이터를 주고 받을 때는, 문자만 주고 받기 가능. 
fetch('https://codingapple1.github.io/price.json')
  .then(res => res.json()) // fetch() 로 가져온 결과(json)를 array/object로 바꿈. 
  .then(function(data){
  console.log(data);
})


create html

1
2
3
4
5
6
let tag_p = document.createElement('p');
tag_p.innerHTML = 'for test';
document.querySelector('#test').appendChild(tag_p);

let a = '<p>FOR TEST</p>';
document.getElementById('test').insertAdjacentHTML('beforeend',a);


add / remove class

1
2
3
4
5
6
7
8
9
document.querySelector('.black-bg').classList.add('aaa', 'bbb');
document.querySelector('.black-bg').classList.remove('aaa');
document.querySelector('.black-bg').classList.contains('aaa', 'bbb') // 한 개라도 일치하지 않으면 false 반환.
document.querySelector('.black-bg').classList.toggle('aaa');

$('.black-bg').addClass('aaa')
$('.black-bg').removeClass('aaa').addClass('bbb')
$('.black-bg').hasClass('aaa bbb'); 
$('.black-bg').toggleClass('aaa');


target, this, preventDefault, stopPropagation

1
2
3
4
5
6
7
document.getElementsByClassName('black-bg')[0].addEventListener('click', function(e){
  console.log(e.target) // 실제 클릭한 요소 알려줌 (이벤트 발생한 곳)
  console.log(e.currentTarget) // this 와 같음. 
  console.log(this)
  console.log(e.preventDefault());
  console.log(e.stopPropagation()); // 내 상위요소로의 이벤트 버블링을 중단해줌
})


deep copy, filter, sort, map

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
32
33
34
35
36
37
38
39
40
// deep copy
var products = [
  { id : 0, price : 70000, title : 'Blossom Dress' },
  { id : 1, price : 50000, title : 'Springfield Shirt' },
  { id : 2, price : 60000, title : 'Black Monastery' }
];

let copyProducts = JSON.parse(JSON.stringify(products));

// arr.filter()
let arr = [1,2,3,4,5,6,7];
let sortedArr = arr.filter(function(value){
  return value > 2;
})

// arr.sort()
let sortProducts = copyProducts.sort(function(a,b){
  if(a.title > b.title)  {
    return 1;
  } else {
    return -1;
  }
})

// arr.map()
let wonToDollar = copyProducts.map(function(product){
  return (product.price / 1000).toFixed(); // 반올림
})

// JS로는 한번에 여러 노드에 이벤트를 주지 못함. 
// document.querySelectorAll('.purchase').addEventListener('click', function(){
//   alert('')
// })
function clickEvent(){
  $('.purchase').on('click', function(e){
    let title = $(e.target).siblings('h5').text()
    console.log(title);
  })
}


localStorage - 세션과 상관없이 저장한 데이터 유지

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
const obj = {  name : 'anna',  age : 20} 
const arr = [1, 2, 3]; 

// 객체, 배열을 JSON 문자열로 변환 후 저장. 
const objString = JSON.stringify(obj);
const arrString = JSON.stringify(arr); 

localStorage.setItem('person', objString);
localStorage.setItem('nums', arrString); 

// JSON 문자열을 객체, 배열로 변환
const personObj = JSON.parse(localStorage.getItem('person'));
const numsArr = JSON.parse(localStorage.getItem('nums'));

for(let i = 0; i < localStorage.length; i++) {  
  // key 찾기  
  const key = localStorage.key(i);    
  // value 찾기  
  const value = localStorage.getItem(key);    
}

for(const key in window.localStorage) {  
  const value = window.localStorage.getItem(key);
}

localStorage.removeItem('person'); // 특정 값 삭제
localStorage.length; // 저장된 값 개수
localStorage.clear(); // 저장된 모든 값 제거


setTimeout(), setInterval()

1
2
3
4
5
6
7
8
9
10
11
12
13
setTimeout(function(){
  document.getElementsByClassName('alert-danger')[0].style.display = 'none';
}, 5000)

let num = 5;

let timer = setInterval(function(){
  if(num > 0) {
      document.getElementsByClassName('alert-danger')[0].children[0].innerHTML = --num;
  } else {
      clearInterval(timer);
  }
}, 1000)