动态检测html元素属性的变化

Detect html element property changes dynamically

本文关键字:变化 属性 元素 检测 html 动态      更新时间:2023-09-26

我有两个按钮- A和B。如果A被禁用/启用,我希望B始终是相同的。

是否有一个简单的方法在JavaScript中做到这一点?

让我们假设没有点击事件等。我只是想监控A和B的状态变化。

// WITH CLICK ----------------------------------------------------
/*
$("#dissablebtnA").on("click", function() {
  $("#btnA").attr("disabled", "disabled");
  if ($("#btnA").attr("disabled") == "disabled") {
    console.log("dissabled button B because button A is disabled");
    $("#btnB").attr("disabled", "disabled");
  }
});
*/
// WITHOUT CLICK ----------------------------------------------------
/*
If you just want to monitor it without clicking you could do like this 
*/
// check every 5 seconds to see if it is dissabled and set b to dissabled accordingly
window.setInterval(function(){
  
 if ($("#btnA").attr("disabled") == "disabled") {
    console.log("dissabled button B because button A is disabled");
    $("#btnB").attr("disabled", "disabled");
   
  }
}, 5000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<button id="btnA">button A</button>
<button id="btnB">button B</button>
<br>
<br>
<button id="dissablebtnA">DISABLE BUTTON A</button>