JS30 15~17강을 진행하면서 배운내용을 정리해두려 합니다.
1. This와 Event.target은 다를수 있다.
<ul class="plates">
<li>
<input type="checkbox" data-index=${i} id="item${i}" ${plate.done ? 'checked' : ''} />
<label for="item${i}">${plate.text}</label>
</li>
</ul>
const itemsList = document.querySelector('.plates');
itemsList.addEventListener('click', handleChecked)
function handleChecked(e) {
console.log(this, e.target) //this는 ul e.target은 input과 label로 2개가 나온다.
}
위의경우 this는 이벤트리스너가 붙은 것을 가리키며(이벤트를 감시하는 객체) e.target은 이벤트가 발생한지점을 나타낸다.
다만 currentTarget은 항상 this와 같음.
https://poiemaweb.com/js-event#71-event-property
2. 리스트에 리스트항목을 JS에서 추가하는 방법
function populateList(plates = [], platesList) {
platesList.innerHTML = plates.map((plate, i) => {
return `
<li>
<input type="checkbox" data-index=${i} id="item${i}" ${plate.done ? 'checked' : ''} />
<label for="item${i}">${plate.text}</label>
</li>
`;
}).join('');
map 함수로 elements의 문자열 배열을 만든후 join으로 하나의 긴 문자열로 합친뒤 innerHTML로 할당하여 리스트 아이템을 변경해줄 수 있다.
3.Local storage 의 Key, Value 페어는 문자열 형태로 저장해야한다.
const item = {
text: text,
done: false
};
localStorage.setItem('items', item) //이렇게하면 정상적으로 작동하지 않는다.
const item = {
text: text,
done: false
};
localStorage.setItem('items', JSON.stringify(item)) //JSON메소드를 활용해 문자열로 바꿔서 저장해야 정상 작동한다.
4. 이벤트 좌표 및 element 위치 찾기
//특정 DOM 요소의 너비와 높이
element.offsetWidth
element.offsetHeight
//이벤트의 발생위치
event.offsetX
event.offsetY
5.정규표현식을 이용해서 문자열을 더 쉽게 찾아낼수있다.
const bands = ['The Plot in You', 'The Devil Wears Prada', 'Pierce the Veil', 'Norma Jean', 'The Bled', 'Say Anything', 'The Midway State', 'We Came as Romans', 'Counterparts', 'Oh, Sleeper', 'A Skylit Drive', 'Anywhere But Here', 'An Old Dog'];
//정규식을 몰라서 내가 처음 길게 작성한 함수
function sorting(fe, se) {
if (fe.includes('The ') || fe.includes('A ') || fe.includes('An ')) {
fe = fe.replace('The ', '');
fe = fe.replace('A ', '');
fe = fe.replace('An ', '');
}
if (se.includes('The ') || se.includes('A ') || se.includes('An ')) {
se = se.replace('The ', '');
se = se.replace('A ', '');
se = se.replace('An ', '');
}
return (fe > se) ? 1 : -1;
}
//정규식을 이용해서 더 간결하게 작성한 함수
function sorting(fe, se) {
const regex = /^The |^An |^A /;
fe = fe.replace(regex, '')
se = se.replace(regex, '')
return (fe > se) ? 1 : -1;
}
bands.sort(sorting);
'TIL > HTML, CSS, JS 이것저것' 카테고리의 다른 글
JS30- Sticky Nav / Event Capture, propagation (0) | 2021.06.23 |
---|---|
JS30 - Follow Along Link Highlighter (0) | 2021.06.21 |
JS30-Slide in on Scroll (0) | 2021.06.15 |
JS30-Video Player (0) | 2021.06.12 |
JS30-Checkboxes (0) | 2021.06.06 |
댓글