问题
I added addEventListener click, drop, dragover on new child created div element. On the new created div element the click works, but the drop and the dragover do not work. How can every new child-div get drop-drag-div? I can not figure out where I made a mistake. Is there any solution?
add Event Listener ('click') - work, add Event Listener ('drop') - do not work, add Event Listener ('dragover') - do not work.
<style>
#divs{
width: 450px;
height: 70px;
margin: 10px;
padding: 10px;
background-color: blue;
}
#dragdiv{
width: 50px;
height: 50px;
margin: 10px;
float: left;
background-color: green;
}
#parent{
width: 450px;
height: 270px;
margin: 10px;
padding: 10px;
background-color: blue;
}
#child{
width: 430px;
height: 70px;
margin: 10px;
float: left;
background-color: red;
}
</style>
<div id="divs" ondrop="drop(event)" ondragover="allowDrop(event)" >
<div id="dragdiv" draggable="true" ondragstart="drag(event)" ></div>
</div>
<button type="button" onclick="AddChild()" >Add Child</button>
<div id="parent">
<div id="child" ondrop="drop(event)" ondragover="allowDrop(event)" ></div>
</div>
<script>
var div = document.getElementsByTagName("div");
var divCount = div.length;
var clickedDivId
for (var i = 0; i < divCount; i += 1) {
div[i].onclick = function(e) {
clickedDivId = this.id;
event.stopPropagation();
alert(this.id);
};
}
function AddChild(){
var y = document.createElement('div');
y.id = 'child'+(i+1);
y.style.width = '430px';
y.style.height = '70px';
y.style.margin = '10px';
y.style.backgroundColor = 'red';
y.style.float = 'left';
document.getElementById("parent").appendChild(y); i+=1;
y.addEventListener('click', function (e) { event.stopPropagation();
clickedDivId = this.id;
alert(this.id); }, false);
y.addEventListener('drop', function ondrop(event) { event.stopPropagation(); }, false);
y.addEventListener('dragover', function ondragover(event) { event.stopPropagation(); }, false);
}
</script>
<script>
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("text", ev.target.id);
}
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data));
}
</script>
来源:https://stackoverflow.com/questions/56204946/add-event-listener-on-new-element-does-not-work