javascript - 我无法将事件绑定到元素
问题描述
const color = ['red', 'orange', 'yellow', 'green', 'blue', 'navy', 'purple'];
let a = [];
for (let i = 0; i < color.length; i++) {
a[i] = document.createElement("input");
a[i].type = 'button';
a[i].id = 'b' + (i + 1);
a[i].value = color[i];
a[i].addEventListener('click', function() {
alert('color');
})
document.body.appendChild(a[i]);
document.body.innerHTML += "<br>"
console.log(a[0].innerHTML);
}
尽管addEventListener
. 问题是什么?
解决方案
问题是,当与innerHTML
容器的 (例如,与 your document.body.innerHTML += "<br>"
)连接时,容器将被清空,然后用新的 HTML 字符串重新解析。如果您之前将侦听器附加到容器中的元素,则该侦听器将不在 HTML 字符串中,因此它不会转移到相同位置的新元素。
const div1 = document.querySelector('#somediv');
document.body.innerHTML += '';
const div2 = document.querySelector('#somediv');
console.log(div1 === div2);
// False, the container's contents were re-parsed, the new div is different!
<div id="somediv"></div>
br
使用与您用于的相同appendChild
方法附加您的a[i]
:
const color = ['red', 'orange', 'yellow', 'green', 'blue', 'navy', 'purple'];
let a = [];
for (let i = 0; i < color.length; i++) {
a[i] = document.createElement("input");
a[i].type = 'button';
a[i].id = 'b' + (i + 1);
a[i].value = color[i];
a[i].addEventListener('click', function() {
alert('color');
})
document.body.appendChild(a[i]);
document.body.appendChild(document.createElement('br'));
}
或者insertAdjacentHTML
改为使用,它的作用类似于.innerHTML +=
,但不同.innerHTML +=
的是,它不会重新创建容器中的所有元素:
const color = ['red', 'orange', 'yellow', 'green', 'blue', 'navy', 'purple'];
let a = [];
for (let i = 0; i < color.length; i++) {
a[i] = document.createElement("input");
a[i].type = 'button';
a[i].id = 'b' + (i + 1);
a[i].value = color[i];
a[i].addEventListener('click', function() {
alert('color');
})
document.body.appendChild(a[i]);
document.body.insertAdjacentHTML('beforeend', '<br>');
}
推荐阅读
- reactjs - 如何使用 Next.js 和 spring-boot 作为后端服务器?
- python - 如何使用 Python Subprocess 删除数据库模式?
- android - 登录和注销时如何使用 SharedPreferences 控制存储用户数据?
- python - 如何使用 feedparser 解析来自 csv 文件的多个提要?
- google-sheets - 如何连接找到的每一行?
- javascript - 如何在 node.js 中运行子进程时首先完成加载
- ios - 如何在 Swift 中的 UITextField 上应用手机号码模式
- google-places-api - 我想澄清一下是否有可能将评论数量从每个位置 5 增加到所有位置
- c# - 如何在 Electron.NET 中创建子模式窗口?
- samsung-mobile - 如何使用 Bixby 在 Android 活动中的视图上生成“onClick()”事件