在新元素上添加事件监听器不起作用?

时间:2019-05-19 05:12:45

标签: javascript drag-and-drop click listener dom-events

我在新的子级创建的div元素上添加了addEventListener单击,拖放,拖动。在新创建的div元素上,单击有效,但拖放和拖动无效。 每个新的child-div如何获得drop-drag-div? 我不知道我在哪里弄错了。有什么解决办法吗?

添加事件监听器(“点击”)-工作, 添加事件监听器(“放下”)-不起作用, 添加事件监听器('dragover')-不起作用。

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

0 个答案:

没有答案