다음과 같이 JS 클래스를 사용하여 div 태그를 동적으로 만들고 렌더링합니다.
class CreateNote {
constructor(title, body) {
this.title = title;
this.body = body;
this.render = () => {
// Create div 1 & 2 and give them the same class name
const div1 = document.createElement('div');
div1.className = 'notes-inner-container';
const div2 = document.createElement('div');
div2.className = 'notes-prev';
const hr = document.createElement('hr');
hr.className = 'notes__line';
// Nest 'div2' inside 'div1'
div1.appendChild(div2);
div1.appendChild(hr);
/*
Create Paragraph 1 & 2 and give them the same
class name and some text
*/
const p1 = document.createElement('p');
p1.innerText = this.title;
const p2 = document.createElement('p');
p2.className = 'notes-prev__body';
p2.innerText = this.body;
// Nest p 1 & 2 inside 'div2'
div2.appendChild(p1);
div2.appendChild(p2);
// Get the body tag and append everything
const notesDiv = document.querySelector('.notes');
notesDiv.appendChild(div1);
}
}
}
이 div에 이벤트 리스너를 추가해야합니다. 그러나이 div가 실제로 렌더링되는 데 시간이 걸리기 때문에 리스너를 연결하려고하면 계속 null
값 을 반환 합니다. 이 문제에 대해 찾은 해결책은 다음 과 같이 렌더링 메서드 내에 이벤트 리스너를 추가하는 것입니다.
// Previous chunk of code
const div1 = document.createElement('div');
div1.className = 'notes-inner-container';
div1.addEventListener('click', () => {
// Do something;
}
// Next chunk of code
그리고 나는 이것이 나쁜 습관입니까? 그렇다면 어떤 방법으로 하시겠습니까? 더 많은 정보가 필요하시면 알려주세요. 미리 감사드립니다.
아니, 이것은 꽤 표준입니다. 이벤트 리스너를 별도로 정의하고 전달합니다.
// at class level
const handleClick = event => { /* handle onClick event */ }
// inside render method
const div = document.createElement('div')
div.className = 'notes-inner-container'
div.addEventListener('click', handleClick)
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다