Javascript js-跟踪容器没有子元素的时刻
我需要跟踪某个html容器没有子节点的时刻。此时,必须运行一些函数 对于此标记:Javascript js-跟踪容器没有子元素的时刻,javascript,html,Javascript,Html,我需要跟踪某个html容器没有子节点的时刻。此时,必须运行一些函数 对于此标记: <div id="container"> <div class="child square"></div> <div class="child square"></div> <div class="child square"></div> <div class="child square"></di
<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>
当我的容器
为空时:
<div id="container"></div>
如何做到这一点?
钢笔:你可以这样做:
function isEmpty(){
if(container.querySelectorAll('.square').length==0)
alert('container is empty');
}
演示:在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 }
只需将其添加到事件侦听器中。您需要查询子元素计数并相应地发出警报
如果还有任何子元素,您可以签入回调
var container=document.getElementById('container');
var children=container.children;
[]映射调用(子项、函数(元素){
元素addEventListener('click',函数(){
这个。删除();
if(children.length==0){
空();
}
})
});
函数为空(){
警报(“容器为空”);
}
1.
2.
3.
4.
5.
是给你的。它是为这种情况而制定的:
// 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(); */
您可以像在中一样观察您的容器
当容器为空时,总是会发生这种情况。它不会对特定的“用户操作”造成混乱,因此它也可能有助于避免意大利面代码
[].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 }
[].map.call(children, function(elem) {
elem.addEventListener('click', function(){
this.remove();
if(document.getElementById('container').children.length === 0) {
alert('container is empty');
}
})
// 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(); */