MutationObserver网络API是跟踪DOM更改的强大工具。它内置于浏览器中,我们也可以将它与jQuery一起使用
js是一个很小的jQuery插件,它使用Mutation Observer API监视特定容器上的DOM更改。当它检测到一个新子项的附加时,它就会触发一个事件。
1.下载插件并在jquery之后包含jquery.waitforChild.js脚本。
- <script src="/path/to/cdn/jquery.slim.min.js"></script>
- <script src="/path/to/jquery.waitforChild.js"></script>
2.现在让我们将一些元素附加到指定的容器中。
- <ul id="example">
- <li>Item 1</li>
- <li>Item 2</li>
- <li>Item 3</li>
- </ul>
3.现在让我们将一些元素附加到指定的容器中。
- $('#example').append('<li class="fouth">Item 4</li>');
- $('#example').append('<li class="fifth">Item 5</li>');
- $('#example').append('<li class="sixth">Item 6</li>');
- ...
4.调用函数,然后查找所有新添加的元素。
- $('#example').waitforChild({
- onFound: function(child) {
- // do something
- },
- });
5.确定是否仅在第一个匹配的子级上应用onFound函数。默认值:false。
- $('#example').waitforChild({
- onFound: function(child) {
- // do something
- },
- once: true,
- });
6.或者只对特定元素应用onFound函数。
- $('#example').waitforChild({
- onFound: function(child) {
- // do something
- },
- querySelector: 'li.fouth',
- });