创建的新div未显示ID

时间:2019-05-15 09:49:18

标签: html element oncreate

我点击了一个div。通过单击前两次潜水,我会收到警报(this.id)-some_id1或some_id2,这很好。 单击“添加Div”按钮将创建一个新的div some_id3,但是单击新的div不会显示警报(this.id),并且不会注册。我不知道为什么。有想法吗?

<style> 
#some_id1{
  width: 50px;
  height: 50px;
  margin: 10px;
  float: left;
  background-color: red;
}

#some_id2{
  width: 50px;
  height: 50px;
  margin: 10px;
  float: left;
  background-color: red;
}

#some_id3{
  width: 50px;
  height: 50px;
  margin: 10px;
  float: left;
  background-color: red;
}
#parent{
  width: 350px;
  height: 150px;
  margin: 10px;
  padding: 10px;
  background-color: blue;
}

#parent2{
  width: 150px;
  height: 150px;
  margin: 10px;
  padding: 10px;
  background-color: blue;
}
</style>

<button type="button" onclick="AddDiv()" >Add Div</button>

<div  id="parent">
<div  id="some_id1"></div>
<div  id="some_id2"></div>
</div>

<div  id="parent2"></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) {
        event.stopPropagation();
        clickedDivId = this.id;
        alert(this.id);
    };
}

function AddDiv(){
  var y = document.createElement('div');
  y.id = 'some_id3';
  document.getElementById("parent").appendChild(y);
}        
</script>

1 个答案:

答案 0 :(得分:1)

您需要为动态创建的元素添加事件监听器。

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;
        alert(this.id);
    };
}

function AddDiv(){
console.log(i);
  var y = document.createElement('div');
 // event.stopPropagation();
 
  y.id = 'some_id'+(i+1);
  y.addEventListener('click', function (e) {
    clickedDivId = this.id;
     alert(this.id);
  }, false);


  document.body.appendChild(y);
  i+=1;
}
div[id^=some_id] {
    width: 50px;
  height: 50px;
  margin: 10px;
  float: left;
  background-color: red;
}
<button type="button" onclick="AddDiv()" >Add Div</button>

<div  id="some_id1"></div>
<div  id="some_id2"></div>