js - 跟踪容器没有子元素的时刻

我需要跟踪某个html容器没有子节点的时刻。此时,必须运行一些功能。js - 跟踪容器没有子元素的时刻

对于此标记:

<div id="container"> 

<div class="child square"></div>

<div class="child square"></div>

<div class="child square"></div>

<div class="child square"></div>

<div class="child square"></div>

</div>

每个square大干快上点击删除:

var container = document.getElementById('container'); 

var children = container.children;

[].map.call(children, function(elem) {

elem.addEventListener('click', function(){

this.remove();

})

});

,当我container是空的:

<div id="container"></div> 

我需要运行一些功能,比方说

function isEmpty(){ 

alert('container is empty');

}

如何做到这一点? 一支笔:https://codepen.io/t411tocreate/pen/vWbrJW?editors=1111

回答:

MutationObserver是给你的。它针对这种情况提出:

// new Observer 

var observer = new MutationObserver(function(mutations) {

mutations.forEach(function(mutation) {

if (mutation.type === 'childList') {

console.log(mutation.target.children.length);

if (!mutation.target.children.length) {

isEmpty()

}

}

});

});

// only observe childList changes

var config = { attributes: false, childList: true, characterData: false };

// start observation

observer.observe(container, config);

// switch off?

/* observer.disconnect(); */

你可以观察你的容器在https://codepen.io/sebilasse/pen/MOLXqw?editors=1111

当容器是空的它总是会发生。它不会混淆特定的“用户操作”,因此它也可能有助于避免意大利面代码...

回答:

你可以做这样的事情:

function isEmpty(){ 

if(container.querySelectorAll('.square').length==0)

alert('container is empty');

}

演示:https://codepen.io/anon/pen/EbrRpN?editors=1111

回答:

添加支票存入的onclick功能。

[].map.call(children, function(elem) { 

elem.addEventListener('click', function(){

this.remove();

let remainingChildren = document.querySelectorAll('#container .child');

if(remainingChildren.length == 0) {doSomething() };

})

})

function doSomething() { // code goes here }

回答:

只需在您的事件监听器中添加此项即可。您需要查询子元素数并相应地发出警报。

WORKING DEMO

[].map.call(children, function(elem) { 

elem.addEventListener('click', function(){

this.remove();

if(document.getElementById('container').children.length === 0) {

alert('container is empty');

}

})

回答:

你可以在回调检查是否有任何的子元素左

var container = document.getElementById('container');  

var children = container.children;

[].map.call(children, function(elem) {

elem.addEventListener('click', function(){

this.remove();

if (children.length == 0) {

empty();

}

})

});

function empty(){

alert('container is empty');

}

<div id="container">  

<div class="child square">1</div>

<div class="child square">2</div>

<div class="child square">3</div>

<div class="child square">4</div>

<div class="child square">5</div>

</div>

以上是 js - 跟踪容器没有子元素的时刻 的全部内容, 来源链接: utcz.com/qa/260287.html

回到顶部