删除动态添加的_parent_ div

时间:2017-06-20 17:42:03

标签: javascript

我有一个动态添加div的功能,我需要的是一个内部按钮,删除这个 div。例如:点击一个按钮,就会添加一个div,里面有一个按钮。单击该按钮后,div将被删除。这是我添加div的代码:

function newTextQuestion() {
var div = document.createElement('div');

div.style.borderLeft = "3px solid #00897b";
div.style.marginBottom = "20px";
div.style.paddingLeft = "10px";
div.style.backgroundColor = "white";

div.className = 'q';
div.setAttribute('data-type', '0');

var name = "random-" + parseInt(Math.random() * 1000000000);
div.innerHTML = '<h5>Tekstiküsimus:</h5><input class="text" name="' + name + '" type="text" placeholder="Küsimuse tekst..." oninvalid="this.setCustomValidity(\'\See väli on kohustuslik!\'\)" oninput="setCustomValidity(\'\'\)" required>';
document.getElementById('questionnaireDiv').appendChild(div);

}

---编辑---

到目前为止我尝试了什么:

function newTextQuestion() {
    var div = document.createElement('div');

div.style.borderLeft = "3px solid #00897b";
div.style.marginBottom = "20px";
div.style.paddingLeft = "10px";
div.style.backgroundColor = "white";

var delbutton = document.createElement('button');
var delbuttontext = document.createElement('X');
delbutton.appendChild(delbuttontext);
delbutton.setAttribute("onclick", function() { $(this).parent().remove(); });

div.appendChild(delbutton);

div.className = 'q';
div.setAttribute('data-type', '0');

var name = "random-" + parseInt(Math.random() * 1000000000);
div.innerHTML = '<h5>Tekstiküsimus:</h5><input class="text" name="' + name + '" type="text" placeholder="Küsimuse tekst..." oninvalid="this.setCustomValidity(\'\See väli on kohustuslik!\'\)" oninput="setCustomValidity(\'\'\)" required>';
    document.getElementById('questionnaireDiv').appendChild(div);

}

1 个答案:

答案 0 :(得分:1)

如果您需要事件处理功能,请不要通过.innerHTML创建元素,请使用document.createElement()技术。要创建按钮,只需遵循您已经开始的相同技术。

此外,最好使用CSS类,而不是设置单个属性。

var parent = document.getElementById('questionnaireDiv');
  
function newTextQuestion() {
  var div = document.createElement('div');

  div.classList.add("newDiv");
  div.classList.add("q");
  
  div.setAttribute('data-type', '0');

  var name = "random-" + parseInt(Math.random() * 1000000000);
  
  var h5 = document.createElement("h5");
  var input = document.createElement("input");
  input.type = "text";
  input.classList.add("text");
  input.placeholder = "Küsimuse tekst...";
  input.required = true;
  
  input.addEventListener("invalid", function(){
    this.setCustomValidity("\'See väli on kohustuslik!\'");
  });
  
  input.addEventListener("input", function(){
    this.setCustomValidity("");
  });

  
  var btn = document.createElement("button");
  btn.textContent = "Delete";

  div.appendChild(h5);
  div.appendChild(input);  
  div.appendChild(btn);
  
  btn.addEventListener("click", function(){
    parent.removeChild(div);
  });
  parent.appendChild(div);
}

newTextQuestion();
.newDiv {
  border-left: 3px solid #00897b;
  margin-bottom: 20px;
  padding-left: 10px;
  background-color:"white";
}
<div id="questionnaireDiv"></div>