我如何更改以下代码(使 timeago 插件工作)以使用 on() 函数(或其他函数),以便可以实时使用?我似乎不太明白(我对 JQuery 还很陌生)。
jQuery(document).ready(function() {
jQuery("a.timeago").timeago();
});
这将如何完成?
最佳答案
您可以使用 MutationObserver 来检查 DOM 何时被修改:https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
您选择一个要观察的节点。对于您的项目,您应该观察容器 a.timeago
元素将被创建到。 <body>
很好,但会给浏览器带来更多的工作。然后,每当 dom 发生变化时,就会触发回调。捕捉您关心的元素。
根据文档修改:
// select the target node
var target = document.querySelector('#your-container');
// create an observer instance
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
mutation.addedNodes.forEach(function(addedNode) {
// if the addedNode matches $('a.timeago')
// $(addedNode).timeago();
});
});
});
// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true };
// pass in the target node, as well as the observer options
observer.observe(target, config);
// later, you can stop observing
observer.disconnect();
关于javascript - Timeago 插件始终开启(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18808844/