<分区>
我正在聊天并且有聊天包装器。在 chat-wrapper 中,新的跨度是用消息创建的。像这样:
<div id="chat-wrapper">
<span>msg 1</span>
<span>msg 2</span>
<span>msg ...</span>
</div>
有没有办法观察#chat-wrapper 是否生下新 child ?
最好是jquery..
标签 javascript jquery
<分区>
我正在聊天并且有聊天包装器。在 chat-wrapper 中,新的跨度是用消息创建的。像这样:
<div id="chat-wrapper">
<span>msg 1</span>
<span>msg 2</span>
<span>msg ...</span>
</div>
有没有办法观察#chat-wrapper 是否生下新 child ?
最好是jquery..
最佳答案
使用Mutation Observer,示例如下:
function addNew() {
var targetNode = document.getElementById('chat-wrapper');
targetNode.innerHTML += '<span> Message' + targetNode.querySelectorAll('span').length + '</span>';
}
window.onload = function() {
var targetNode = document.getElementById('chat-wrapper');
var config = {
attributes: true,
childList: true,
subtree: true
};
var observer = new MutationObserver(callback);
observer.observe(targetNode, config);
}
// Callback function to execute when mutations are observed
var callback = function(mutationsList) {
for (var mutation of mutationsList) {
if (mutation.type == 'childList') {
console.log('A child node has been added or removed.');
} else if (mutation.type == 'attributes') {
console.log('The ' + mutation.attributeName + ' attribute was modified.');
}
}
};
<div id="chat-wrapper">
</div>
<button onclick='addNew()'>Add New</button>
关于javascript - 当新子元素出现在 html 元素中时触发事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51476691/
相关文章:
javascript - BackBone 集合获取参数进行重复调用但不起作用
javascript - TinyMCE:格式化我的tinymce编辑器会杀死django功能
javascript - ajax表单提交后手动重置jquery star插件
javascript - 在 Internet Explorer 上使用 jquery 时出现问题
javascript - SetInterval/ClearInterval 循环无法正常运行
javascript - JSDoc @param 和 @deprecated
javascript - 编辑 php 文件模板在 Wordpress 上不生效
javascript - 在窗口调整大小和加载时将 div 高度与父级匹配
javascript - 解决错误: Cannot read property 'style' of null"with a better approach?