听取更改按钮的类名称

时间:2016-11-15 10:23:33

标签: javascript html dom

我想要编写JavaScript代码,该代码应该从DOM中更改元素的类名并执行如下函数...

function(){
  console.log("Catch class name change!");
}

我有按钮......

<button class="btn-large red" data-bind="text: submitLabel, trueClick: submit,
          css: { 'light-skin': ff.DealTicket.useLightSkin, disabled: !isValid() || isOrderPending() ||isSubmitting(), blue: isBuy(), red: !isBuy(), yellow: isOCO() }">Place Sell Trade</button>

...从

更改自己的班级名称

<button class="btn-large red">...

<button class="btn-large red dissabled">...

我通过

获得此按钮

document.querySelector('btn-large.red');

如何收听更改此名称类值?

我尝试使用eventListener和DOMCOntentLoad,DOMSubtreeModified但它不起作用。

document.querySelector("btn-large.red").addEventListener("DOMContentLoaded", function(){
        console.log("Catch class name change!");
    });

1 个答案:

答案 0 :(得分:2)

您可以使用mutation observer收听元素属性的更改;添加/删除类时,class属性会更新。

示例:

&#13;
&#13;
// The function to call when the class changes
function classChanged(b) {
  console.log("The class changed: " + b.className);
}

// The button
var btn = document.getElementById("the-button");
console.log("Initial class: " + btn.className);

// The mutation observer
var ob = new MutationObserver(function() {
   classChanged(btn);
});
ob.observe(btn, {
  attributes: true,
  attributeFilter: ["class"]
});

// Just for our example, something to periodically modify
// the classes on the button
var timer = setInterval(function() {
  btn.classList.toggle("fuzz");
  btn.classList.toggle("bizz");
}, 500);
setTimeout(function() {
  console.log("Done");
  clearInterval(timer);
}, 10000);
&#13;
.foo {
  color: blue;
}
.bar {
  color: green;
}
&#13;
<button id="the-button" class="foo fuzz">This is the button</button>
&#13;
&#13;
&#13;