【问题标题】:Listen for children count of an element in Javascript [duplicate]侦听Javascript中元素的子项计数[重复]
【发布时间】:2021-05-02 08:56:51
【问题描述】:

我正在使用 jquery,我想在计算元素的子元素数量后执行一个函数。 我的元素有一个孩子,我想在它变成 2 个或更多之后执行一个函数。 这个子附加由其他一些 JavaScript 文件处理,我只想听在那个元素中添加一个子。 该附加子项发生在异步操作之后,因此在检查子项计数时可能不会执行。 这是我尝试过的:

let i = 0;
const interVal = setInterval(() => {
    const parent = $(".parent");

    if (parent && parent.length > 1) {
        console.log("Child has been appended.");
    } else {
        console.log("Child has not been appended!");

        if (i >= 50000) {
            console.error("A lot of conditions executed and cannot bother browser anymore.");

            clearInterval(interVal);
        }
    }

    i++;
}, 1);

这段代码有问题。 它在一段时间后检查。 我可以用它代替什么?

【问题讨论】:

  • 请向我们展示您的代码以及您尝试过的内容
  • 嗨,欢迎来到 SO。请花时间阅读tourHow to Ask 页面。

标签: javascript jquery dom browser


【解决方案1】:

其实都是if-else。

让我给你解释一下。

<div id="parent">
  <ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
    <li>6</li>
  </ul>
</div>

要达到孩子的数量,您应该像这样使用 .length;

var count = $("#parent li").length;

或者这样

var count = $("#parent ul").children().length;

现在假设如果孩子的数量大于 2 或任何你想要的,你想要执行;

if(count>2){
    alert("I am bigger than 2, mate");
}

【讨论】:

  • 子附加发生在异步操作之后。所以也许那个时候没有附加。
【解决方案2】:

MutationObserver 是您所需要的。

这是 MDN 示例,稍作修改。

// simulating some content appended in a later time (async)
setTimeout(function () {
  $(".parent").append("<div>I am a div appended after page load!</div>");
}, 5000);

// Mutation observer
var targetNode = $(".parent")[0];

// Options for the observer (which mutations to observe)
const config = { attributes: true, childList: true, subtree: true };

// Callback function to execute when mutations are observed
const callback = function (mutationsList, observer) {
  // Use traditional 'for loops' for IE 11
  for (const mutation of mutationsList) {
    if (mutation.type === "childList") {
      console.log("A child node has been added or removed.");

      // How many children now?
      console.log(`There is ${$(".parent").children().length} child elements`);
      
      // List them
      $(".parent").children().each(function(index){
        console.log(`#${index+1}- ${$(this)[0].tagName} - ${$(this)[0].innerText}`)
      })
      
    } else if (mutation.type === "attributes") {
      console.log("The " + mutation.attributeName + " attribute was modified.");
    }
  }
};

// Create an observer instance linked to the callback function
const observer = new MutationObserver(callback);

// Start observing the target node for configured mutations
observer.observe(targetNode, config);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="parent">
  <h1>Hello! Another child will be appended...</h1>
</div>

结束observer...就像在某个时候达到某个条件...使用:

observer.disconnect();

【讨论】:

    猜你喜欢
    • 2017-07-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-28
    • 2016-11-16
    • 1970-01-01
    • 2013-08-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多