简体   繁体   English

使用“ this”和Javascript删除div

[英]Delete a div using “this” with Javascript

What I would like to do is to create a div by clicking on a button. 我想做的是通过单击一个按钮来创建一个div。 In that div there will be another button if clicked will delete the div that it is in. So potentially the first button will create many div's with this delete button inside but I want the delete button to only delete the div that it is within. 在该div中,如果单击另一个按钮,则将删除其所在的div。因此,第一个按钮可能会创建多个div,并且其中包含该delete按钮,但我希​​望Delete按钮仅删除它所在的div。 Any suggestions? 有什么建议么?

If you do not need to keep the "delete button" on your page, bind the click event on each of them and use .removeChild on the parent element of the parent div. 如果不需要在页面上保留“删除按钮”, click在每个事件上绑定click事件,并在父div的父元素上使用.removeChild
FIDDLE DEMO 现场演示

You can do something like: 您可以执行以下操作:

<script>

var addDiv = (function() {
  var div = document.createElement('div');
  div.appendChild(document.createTextNode('some text'));

  var button = document.createElement('button');
  button.appendChild(document.createTextNode('Remove...'));
  button.type = "button";


  return function() {
    var d = div.cloneNode(true);
    var b = button.cloneNode(true);
    b.onclick = function() {
      var d = this.parentNode;
      d.parentNode.removeChild(d);
    };
    d.appendChild(b);
    document.body.appendChild(d);
  };
}())

</script>

<button onclick="addDiv()">Add a div</button>

The above is just a trivial example to demonstrate one way to go about it. 上面只是一个简单的示例,展示了解决该问题的一种方法。 Note that if you clone an element, listeners added as properties or by addEventListener are dropped (this script would be very much simpler if they weren't). 请注意,如果您克隆一个元素,则会删除作为属性或通过addEventListener添加的侦听器(如果没有,则此脚本会非常简单)。

HTML: HTML:

<input type="button" id='create' value="Create div!"/>

JS: JS:

var i = 0;
document.onclick = function(e) {
    var t = e.target;
  if(t.id == 'create'){
     t.parentNode.innerHTML += '<div>I AM A CHILD '+(++i)+' <input type="button" class="child" value="DELETE ME!"/><br/></div>';
    }
  if (t.className == 'child') {
    t.parentNode.outerHTML = '';
  }
};

using document.onclick and detecting the target element can be used as a live click to monitor newly created divs. 使用document.onclick并检测目标元素可用作实时单击以监视新创建的div。

Its early and my brain may be a little foggy and the code may be a little dirty 它的早期和我的大脑可能有点模糊并且代码可能有点脏

Here is a jsfiddle 这是一个jsfiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM