javascript - 如何在不使用 ID 的情况下删除 div

标签 javascript html parent removechild

每次更新都会创建 Div,它们的位置在“levelWrapper”内随机化。所有这些 div 共享一个名为 tree 的类。每当我单击以 tree 作为类的 div 时,代码都会遍历所有现有的 tree 类 div,并比较它们相对于鼠标单击坐标的位置。如果它们的位置在点击范围内(即 100 像素),则我想删除所述 div

这是我已经完成我想要的功能 但是在第一次运行代码后出现错误。我认为我知道它为什么会出现错误,请阅读下文。

var i = 0,
  a = 0;

function newTree() {
  var newTree = document.createElement('div');
  newTree.id = 'tree' + i;
  newTree.className = 'tree';
  document.getElementById("levelWrapper").appendChild(newTree);
}

function positionTree() {
  var levelWidth = document.getElementById("levelWrapper").offsetWidth;
  var levelHeight = document.getElementById("levelWrapper").offsetHeight;

  var treeX = Math.round(Math.random() * levelWidth);
  var treeY = Math.round(Math.random() * levelHeight);

  document.getElementById("tree" + i).style.left = treeX + "px";
  document.getElementById("tree" + i).style.top = treeY + "px";
}

function createTree() {
  a += 1;
  if (a == 20) {
    newTree(); // new div
    positionTree(); // position div
    a = 0; // reset counter for new div
    i++; // new ID for new div
  }
}

function getMouseCoordinates(e) {
  var offset = $('#levelWrapper').offset();
  mouseX = Math.round(e.clientX - offset.left);
  mouseY = Math.round(e.clientY - offset.top);
}

var clickRange = 100;

function update() {
  createTree();

  $('div.tree').click(function(e) {
    getMouseCoordinates(e);
    var numItems = $('.tree').length;

    for (g = 0; g < numItems; g++) {
      var p = $("#tree" + g).position();

      if ((p.left > (mouseX - clickRange)) &
        (p.left < (mouseX + clickRange)) &
        (p.top > (mouseY - clickRange)) &
        (p.top < (mouseY + clickRange))) {

        p = document.getElementById("tree" + g);
        p.parentNode.removeChild(p);
      }
    }
  });
}

function mainLoop() {
  update();
  requestAnimationFrame(mainLoop);
}

requestAnimationFrame(mainLoop);
#levelWrapper {
  position: relative;
  top: 25px;
  width: 1100px;
  height: 700px;
  margin: auto;
  border: 1px solid red;
}

.tree {
  position: absolute;
  background: green;
  height: 12px;
  width: 12px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div id="levelWrapper"></div>

它会出现错误,因为在第二次运行时,这行 var p = $("#tree"+ g).position(); 选择了一个已被删除的 div,因此它返回 null。

仍会创建新的 div,但单击/删除功能停止工作。

我可能可以做一些类似“if (null) ...”的事情,但是 div ID 不断增加,很容易达到 for 循环必须经过的 200 多个 div,而且速度明显很慢。

因此,我没有通过 ID 删除 div,而是考虑使用一些数组引用它们,每当我删除一个 div 时,数组就会“级联”下来,减少我必须执行的检查量,并避免每次都返回 null它尝试找到已删除 div 的左侧和顶部偏移量。

最佳答案

  1. 测试是否存在:
<小时/>
   for (g = 0; g < numItems; g++) {
      var $div = $("#tree" + g);
      if ($div.length==0) continue;
      var p = $div.position();

      if ((p.left > (mouseX - clickRange)) &
        (p.left < (mouseX + clickRange)) &
        (p.top > (mouseY - clickRange)) &
        (p.top < (mouseY + clickRange))) {

        $div.remove();
      }
    }
  • 委托(delegate) - 每次循环时添加一个点击处理程序
  • <小时/>
     $('#levelWrapper').on('click','div.tree',function(e) {
      getMouseCoordinates(e);
      $('.tree').each(function() {
        var p = $(this).position();
    

    var i = 0,
      a = 0;
    
    function newTree() {
      i = $('#levelWrapper').children().length;
      var $newTree = $('<div/>', {
        'id': 'tree' + i,
        'class': 'tree'
      }); // .text(i); 
      $('#levelWrapper').append($newTree);
    }
    
    function positionTree() {
      var levelWidth = document.getElementById("levelWrapper").offsetWidth;
      var levelHeight = document.getElementById("levelWrapper").offsetHeight;
    
      var treeX = Math.round(Math.random() * levelWidth);
      var treeY = Math.round(Math.random() * levelHeight);
    
      document.getElementById("tree" + i).style.left = treeX + "px";
      document.getElementById("tree" + i).style.top = treeY + "px";
    }
    
    function createTree() {
      a += 1;
      if (a == 20) {
        newTree(); // new div
        positionTree(); // position div
        a = 0; // reset counter for new div
        i++; // new ID for new div
      }
    }
    
    function getMouseCoordinates(e) {
      var offset = $('#levelWrapper').offset();
      mouseX = Math.round(e.clientX - offset.left);
      mouseY = Math.round(e.clientY - offset.top);
    }
    
    var clickRange = 100;
    
    
    function mainLoop() {
      createTree();
      requestAnimationFrame(mainLoop);
    }
    
    
    $(function() {
      $('#levelWrapper').on('click','div.tree',function(e) {
        getMouseCoordinates(e);
        $('.tree').each(function() {
          var p = $(this).position();
    
          if ((p.left > (mouseX - clickRange)) &
            (p.left < (mouseX + clickRange)) &
            (p.top > (mouseY - clickRange)) &
            (p.top < (mouseY + clickRange))) {
    
            $(this).remove();
          }
        });
      });
      requestAnimationFrame(mainLoop);
    });
    #levelWrapper {
      position: relative;
      top: 25px;
      width: 1100px;
      height: 700px;
      margin: auto;
      border: 1px solid red;
    }
    
    .tree {
      position: absolute;
      background: green;
      height: 12px;
      width: 12px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <div id="levelWrapper"></div>

    关于javascript - 如何在不使用 ID 的情况下删除 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46473733/

    相关文章:

    javascript - jquery 对象的 "content"是在创建时立即设置的吗?

    javascript - 使用 jsduck 记录事件处理程序的最佳方法是什么?

    html - 如何用jquery mobile实现多列表?

    javascript - 用于以编程方式生成的内容的 ID 的 jQuery 选择器

    javascript - 基于选择更改或输入条目的 JQuery 启用和禁用

    JQuery:当.each超过 parent 具有不同ID的 child 时,第一个 parent 的ID仍然存在

    javascript - 在使用 Javascript 设计注销后自动重定向?

    javascript - ui-router(状态 'dash' 中的无效参数)

    r - 生成从结束到开始顺序配对值的不同长度向量

    java - Java 中的父级枚举