Javascript Can';t将子元素追加到单击的元素
我试图在单击某个元素时将div附加到该元素,但是当我使用.appendChild(div)时,我试图附加到的元素未定义。我很困惑,因为它显然在DOM中,因为我能够检测到对它的点击,我只是不能附加到它Javascript Can';t将子元素追加到单击的元素,javascript,html,dom,Javascript,Html,Dom,我试图在单击某个元素时将div附加到该元素,但是当我使用.appendChild(div)时,我试图附加到的元素未定义。我很困惑,因为它显然在DOM中,因为我能够检测到对它的点击,我只是不能附加到它 var pcells = document.getElementsByClassName('priority-cell'); for (var i=0; i < pcells.length; i++) { pcells[i].onclick = function () { var
var pcells = document.getElementsByClassName('priority-cell');
for (var i=0; i < pcells.length; i++) {
pcells[i].onclick = function () {
var div = document.createElement('div');
div.style.backgroundColor = "red";
div.style.height = "10px";
div.style.width = "10px";
pcells[i].appendChild(div);
};
}
var pcells=document.getElementsByClassName('priority-cell');
对于(变量i=0;i
您有一个范围问题。您需要将事件详细信息传递到处理程序中,并使用target属性来标识单击了哪个单元格
var pcells = document.getElementsByClassName('priority-cell');
for (var i=0; i < pcells.length; i++) {
pcells[i].onclick = function (e) {
var div = document.createElement('div');
div.style.backgroundColor = "red";
div.style.height = "10px";
div.style.width = "10px";
e.target.appendChild(div);
};
}
var pcells=document.getElementsByClassName('priority-cell');
对于(变量i=0;i
(JSFiddle:)我认为问题在于:
var a = [1, 2, 3, 4, 5];
for(var i=0; i < a.length; i++) {
setTimeout(function() {
console.log(i); //5
console.log(a[i]) //undefined;
}, 1000)
}
试试这个:
var pcells=document.getElementsByClassName('priority-cell');
对于(变量i=0;i
点击这里
e.target.appendChild(div)
可以是this.appendChild(div)
-作为,onclick函数中的这一
是pcells[i]:p确实如此,但在风格上我更喜欢明确。您是否回答了其他问题?否!我只是想让他知道为什么会产生这个问题
var a = [1, 2, 3, 4, 5];
for(var i=0; i < a.length; i++) {
(function(index) {
setTimeout(function() {
console.log(index); //1,2,3,4,5
console.log(a[index]) //1,2,3,4,5;
}, 1000)
})(i);
}
for (var i=0; i < pcells.length; i++) {
(function(index) {
pcells[index].onclick = function () {
var div = document.createElement('div');
div.style.backgroundColor = "red";
div.style.height = "10px";
div.style.width = "10px";
pcells[index].appendChild(div);
};
})(i);
}
element.onclick = function(event) {
console.log(this);
console.log(event);
//use 'this' or 'event' do something
}