[英]JQuery how to listen for a element attribute/property change event
JQuery 1.12.1 (inherited and can't be updated to 3) JQuery 1.12.1(继承,不能更新到3)
$('#subBut').onchange(function() {
if($('#subBut').prop('disabled')) {
$('#reasons').slideDown();
}
else {
$('#reasons').slideUp();
}
});
How can I check for when the property of the element changes, and run the change to #reasons
based on that change?如何检查元素的属性何时更改,并根据该更改运行对
#reasons
的更改?
This seems surprisingly hard to do natively and some people point to plugins which I want to avoid and other (very old) questions on here relate to simply not being able to do it!这似乎很难在本地完成,有些人指出我想避免的插件和这里的其他(非常老的)问题与根本无法做到这一点有关!
I need the event to fire when a property on an element changes;当元素上的属性发生变化时,我需要触发事件; the change is caused by a range of other parts of JQuery code so it's best this is seperate and listens independant of what causes the change.
更改是由 JQuery 代码的一系列其他部分引起的,因此最好这是单独的,并且独立于导致更改的原因进行监听。
I tried things like $('#subBut').prop().onchange(function() {
and similar but these are bad syntax.我试过像
$('#subBut').prop().onchange(function() {
和类似的东西,但这些语法不好。
It is NOT the value of the element that changes.改变的不是元素的值。
For reference, PrettyinPink's Comment was what was needed;作为参考, PrettyinPink 的评论是需要的; looking up Mutation Observer rather than the older and more prolific Mutation Event was what was needed:
查找Mutation Observer而不是旧的和更多产的 Mutation Event 是需要的:
// 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
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.