如何在运行时跟踪DIV的子元素计数?

时间:2018-07-23 06:08:29

标签: javascript jquery addeventlistener event-listener

我有一个div,其中将包含下拉列表,这些下拉列表是由用户单击该div外部的按钮后动态创建的。

因此,在这里我需要实现的是在没有下拉菜单时显示“未应用过滤器”,而在存在下拉菜单时删除“未应用过滤器”。

我通过addEventListener尝试了此方案,但是我不确定该方案需要采取什么行动?

document.addEventListener("DOMContentLoaded", function(event) {
  var activities = document.getElementById("dvContainer");
  activities.addEventListener("change", function() {
    if (activities.childElementCount > 0) {
      activities.classList.add("displayZero");
    } else {
      activities.classList.remove("displayZero");
    }
    //console.log('ajay');
  });
});

function AddDropDownList() {}
<input type="button" id="btnAdd" onclick="AddDropDownList()" value="Add Filter" />
<div id="dvContainer"><span>No Filters applied.</span></div>

这是我的尝试,谢谢。

2 个答案:

答案 0 :(得分:0)

根据您提到的内容,您有一个按钮,单击该按钮可以动态添加下拉列表。

所以您不需要任何额外的活动!

在按钮的点击功能中:

yourButton.onclick=function(){
    //..... do somethings similar adding dropdowns
    activities.classList.add("displayZero");
};

以及您删除下拉菜单的位置:

activities.classList.remove("displayZero");

答案 1 :(得分:0)

目前,我只能想到两种解决方法:

  1. 最简单的解决方案是首先创建update函数,然后从dom的init中调用它,然后在AddDropDownList中对其进行调用。例如

function update() {
  if (activities.childElementCount > 0) {
    activities.classList.add("displayZero");
  } else {
    activities.classList.remove("displayZero");
  }
}
window.onload = function() {
  update();
}

function AddDropDownList() {
  //Put Your code as you have written and then add
  update();
}

  1. 使用变异观察者

window.onload = function() {
  // Select the node that will be observed for mutations
  var targetNode = document.getElementById('dvContainer');

  // Options for the observer (which mutations to observe)
  var config = {
    attributes: true,
    childList: true,
    subtree: true
  };
  // Create an observer instance linked to the callback function
  var observer = new MutationObserver(callback);

  // Start observing the target node for configured mutations
  observer.observe(targetNode, config);
}

function AddDropDownList() {

}


// Callback function to execute when mutations are observed
var callback = function(mutationsList) {
  for (var mutation of mutationsList) {
    if (mutation.type == 'childList') {
      console.log('A child node has been added or removed.');
      if (activities.childElementCount > 0) {
        activities.classList.add("displayZero");
      } else {
        activities.classList.remove("displayZero");
      }
    } else if (mutation.type == 'attributes') {
      console.log('The ' + mutation.attributeName + ' attribute was modified.');
    }
  }
};