如何使用jQuery触发类更改事件? [英] How to fire an event on class change using jQuery?

查看:85
本文介绍了如何使用jQuery触发类更改事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望有类似的东西:

$('#myDiv').bind('class "submission ok" added'){
    alert('class "submission ok" has been added');
});


推荐答案

当班级发生变化时,不会引发任何事件。另一种方法是在以编程方式更改类时手动引发事件:

There is no event raised when a class changes. The alternative is to manually raise an event when you programatically change the class:

$someElement.on('event', function() {
    $('#myDiv').addClass('submission-ok').trigger('classChange');
});

// in another js file, far, far away
$('#myDiv').on('classChange', function() {
     // do stuff
});






UPDATE

这个问题似乎是在收集一些访问者,所以这里有一个方法的更新,无需使用新的 MutationObserver修改现有代码

This question seems to be gathering some visitors, so here is an update with an approach which can be used without having to modify existing code using the new MutationObserver:

var $div = $("#foo");
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    if (mutation.attributeName === "class") {
      var attributeValue = $(mutation.target).prop(mutation.attributeName);
      console.log("Class attribute changed to:", attributeValue);
    }
  });
});
observer.observe($div[0], {
  attributes: true
});

$div.addClass('red');

.red { color: #C00; }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo" class="bar">#foo.bar</div>

请注意 MutationObserver 仅适用于较新的浏览器,特别是Chrome 26,FF 14,IE 11,Opera 15和Safari 6.请参阅 MDN 了解更多详情。如果您需要支持旧版浏览器,那么您需要使用我在第一个示例中概述的方法。

Be aware that the MutationObserver is only available for newer browsers, specifically Chrome 26, FF 14, IE 11, Opera 15 and Safari 6. See MDN for more details. If you need to support legacy browsers then you will need to use the method I outlined in my first example.

这篇关于如何使用jQuery触发类更改事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆