2017-06-08 113 views
1

我试图将div附加到元素时单击但是当我使用.appendChild(div)时,我试图附加到的元素是未定义的。我很困惑,因为它明显在DOM中,因为我能够检测到它的点击,我只是不能附加到它。不能追加儿童单击元素

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); 
    }; 
} 
+0

[闭合内部的JavaScript闭包 - 简单实际例子](https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) –

回答

1

您有一个范围界定问题。您需要将事件详细信息传递到您的处理程序,并使用目标属性来确定哪个单元被点击。

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); 
    }; 
} 

(的jsfiddle:https://jsfiddle.net/z3nhprzp/

+0

'e.target.appendChild(div);'可以'this.appendChild(div );' - 作为onclick函数中的'this'是pcells [i]:p –

+0

确实,但在风格上我更喜欢明确。 –

0

我认为这个问题是在这里,如:

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 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 
} 
+0

您是否正在回答不同的问题? – SPlatten

+0

不!我只想让他知道为什么产生这个问题 –

0

试试这个:

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"; 
 

 
     this.appendChild(div); 
 
    }; 
 
}
<div class="priority-cell">CLICK HERE</div>