簡體   English   中英

JQuery 如何監聽元素屬性/屬性更改事件

[英]JQuery how to listen for a element attribute/property change event

JQuery 1.12.1(繼承,不能更新到3)

$('#subBut').onchange(function() {
    if($('#subBut').prop('disabled')) {
        $('#reasons').slideDown();
    }
    else {
        $('#reasons').slideUp();
    }
});

如何檢查元素的屬性何時更改,並根據該更改運行對#reasons的更改?

這似乎很難在本地完成,有些人指出我想避免的插件和這里的其他(非常老的)問題與根本無法做到這一點有關!

當元素上的屬性發生變化時,我需要觸發事件; 更改是由 JQuery 代碼的一系列其他部分引起的,因此最好這是單獨的,並且獨立於導致更改的原因進行監聽。

我試過像$('#subBut').prop().onchange(function() {和類似的東西,但這些語法不好。

改變的不是元素的值。

作為參考, PrettyinPink 的評論是需要的; 查找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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM