我正在使用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实际需要花费一些时间才能呈现,因此当我尝试将侦听器附加到该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] 删除。
我来说两句