问题描述
我正在制作一个计算器,并在数字按钮上添加 eventListeners
。
JS 看起来像这样:
document.addEventListener('click',e =>{
if (e.target.matches('#num1')){
const x = document.createElement('p');
x.innerHTML = e.target.innerHTML;
screen.appendChild(x)
}
else if (e.target.matches('#num2')){
const x = document.createElement('p');
x.innerHTML = e.target.innerHTML;
screen.appendChild(x)
}
else if (e.target.matches('#num3')){
const x = document.createElement('p');
x.innerHTML = e.target.innerHTML;
screen.appendChild(x)
}
})
它工作正常,但显然有 10 个数字按钮,所以我试图用十进制运算符缩短它,或者用这部分制作一个函数:
const x = document.createElement('p');
x.innerHTML = e.target.innerHTML;
screen.appendChild(x)
然而,这种方式 e.target 是未定义的。任何建议表示赞赏!
标记:
<button type='button' class='btn numBtn' id='num1'>1</button>
<button type='button' class='btn numBtn' id='num2'>2</button>
<button type='button' class='btn numBtn' id='num3'>3</button>
解决方法
检查类而不是 ID。
由于您不是故意插入或检索 HTML 标记,因此您还应该使用 textContent
而不是 innerHTML
,它更安全、更快捷且在语义上更合适。
document.addEventListener('click',e =>{
if (e.target.matches('.numBtn')){
const x = document.createElement('p');
x.textContent = e.target.textContent;
screen.appendChild(x)
}
})
您也可以使用 insertAdjacentHTML
,尽管这与 innerHTML
存在相同的问题。
document.addEventListener('click',e =>{
if (e.target.matches('.numBtn')){
screen.insertAdjacentHTML(
'beforeend',`<p>${e.target.textContent}</p>`
);
}
})