JQuery如何侦听元素属性/属性更改事件


JQuery 1.12.1(已继承,无法更新为3(
$('#subBut').onchange(function() {
if($('#subBut').prop('disabled')) {
$('#reasons').slideDown();
}
else {
$('#reasons').slideUp();
}
});

如何检查元素的属性何时更改,并根据该更改运行对#reasons的更改?

这似乎很难在本机上实现,有些人指出我想避免的插件,而这里的其他(非常古老的(问题则与无法实现有关!

当元素上的属性发生更改时,我需要触发事件;更改是由JQuery代码的一系列其他部分引起的,因此最好是分开的,并独立于更改的原因进行侦听。

我尝试了$('#subBut').prop().onchange(function() {之类的东西,但这些都是糟糕的语法。

更改的是元素的值。

作为参考,需要PrettyinPink的Comment;需要查找突变观察者,而不是更老、更多产的突变事件:

// Here we watch for new elements
const observer = new MutationObserver(function () {
console.log('observed!');
if($('#subBut').prop('disabled')) {
$('#reasons').slideDown();
}
else {
$('#reasons').slideUp();
}
});
// Param 1 of observe() must be a Node - document is a valid Node, 
// but not advisable, limit the watcher to as small a context as possible
// Important here to set attributes to be true to check these. 
observer.observe(document.getElementById('subBut'), {
attributes: true
});

最新更新