Javascript dom中的类创建
不推荐使用Javascript dom中的类创建,javascript,jquery,Javascript,Jquery,不推荐使用domanodeinserted。我能找到的MutationObserver的唯一例子是显示正在更新的元素,而不是添加的元素 监听动态创建的特定类的新元素的最佳方式是什么?可能是您要求在添加类后立即触发事件: $(document).on('click', function(){ $('#theid').addClass('classname').trigger('classChange'); }); $('#theid').on('classChange', function()
domanodeinserted
。我能找到的MutationObserver
的唯一例子是显示正在更新的元素,而不是添加的元素
监听动态创建的特定类的新元素的最佳方式是什么?可能是您要求在添加类后立即触发事件:
$(document).on('click', function(){
$('#theid').addClass('classname').trigger('classChange');
});
$('#theid').on('classChange', function() {
// do stuff
});
如果还有其他问题,请解释:您可以通过将正确的
MutationObserver init
传递给MutationObserver
来完成此操作。您必须将子树
设置为真
,并添加属性过滤器
:类
(与domNode的类名相同)
考虑以下示例(基于):
JSFIDLE here:将DOM节点添加到元素会触发父元素的更新事件,对吗
:)
为什么要使用jQuery?@ManinderSingh我正在发出一个ajax请求,然后创建一个带有按钮的表来编辑数据。我想创建另一个js类,在创建按钮时,它可以操纵按钮的外观。我想基本上做一个钩子,这样js文件就可以被放到系统的任何部分,而不需要额外的配置。因此,我只希望能够操纵按钮之外的按钮,我希望我不会只使用Jquery将我的建议搞得一团糟。我的理解是:您希望向动态添加的按钮添加一个类。以便您可以更改其外观或使按钮收听更多事件?是吗?@ManinderSingh需要更改按钮的样式并更新属性
// select the target node
var target = document.getElementById('some-id');
// create an observer instance
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
console.log(mutation);
});
});
// configuration of the observer:
var config = { attributes: true, childList: false, characterData: false, subtree: true, attributeFilter: ['class']};
// pass in the target node, as well as the observer options
observer.observe(target, config);
var myElement = document.createElement('div');
myElement.innerHTML = 'foo';
target.appendChild(myElement);
//triggers the mutation observer
myElement.classList.add('bar');