如何使用jQuery触发类更改事件?

时间:2013-10-16 10:58:08

标签: javascript jquery javascript-events

我希望有类似的东西:

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

4 个答案:

答案 0 :(得分:117)

课程更改时不会引发任何事件。另一种方法是在以编程方式更改类时手动引发事件:

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

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

<强>更新

这个问题好像是在收集一些访问者,所以这里有一个方法的更新,无需使用新的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。如果您需要支持旧版浏览器,那么您需要使用我在第一个示例中概述的方法。

答案 1 :(得分:19)

您可以使用自己的jQuery addClass和removeClass函数替换原始函数,然后触发自定义事件。 (使用自调用匿名函数来包含原始函数引用)

(function( func ) {
    $.fn.addClass = function() { // replace the existing function on $.fn
        func.apply( this, arguments ); // invoke the original function
        this.trigger('classChanged'); // trigger the custom event
        return this; // retain jQuery chainability
    }
})($.fn.addClass); // pass the original function as an argument

(function( func ) {
    $.fn.removeClass = function() {
        func.apply( this, arguments );
        this.trigger('classChanged');
        return this;
    }
})($.fn.removeClass);

然后你的其余代码就像你期望的一样简单。

$(selector).on('classChanged', function(){ /*...*/ });

更新

这种方法确实假设只能通过jQuery addClass和removeClass方法更改类。如果以其他方式修改类(例如通过DOM元素直接操作类属性),则需要使用MutationObserver之类的内容,如此处接受的答案中所述。

另外,对这些方法进行了一些改进:

  • 触发添加(classAdded)或删除(classRemoved)的每个类的事件,并将特定类作为参数传递给回调函数,并仅触发特定类实际上已添加(以前不存在)或删除(以前存在)
  • 如果实际更改了任何类,则仅触发classChanged

    (function( func ) {
        $.fn.addClass = function(n) { // replace the existing function on $.fn
            this.each(function(i) { // for each element in the collection
                var $this = $(this); // 'this' is DOM element in this context
                var prevClasses = this.getAttribute('class'); // note its original classes
                var classNames = $.isFunction(n) ? n(i, prevClasses) : n.toString(); // retain function-type argument support
                $.each(classNames.split(/\s+/), function(index, className) { // allow for multiple classes being added
                    if( !$this.hasClass(className) ) { // only when the class is not already present
                        func.call( $this, className ); // invoke the original function to add the class
                        $this.trigger('classAdded', className); // trigger a classAdded event
                    }
                });
                prevClasses != this.getAttribute('class') && $this.trigger('classChanged'); // trigger the classChanged event
            });
            return this; // retain jQuery chainability
        }
    })($.fn.addClass); // pass the original function as an argument
    
    (function( func ) {
        $.fn.removeClass = function(n) {
            this.each(function(i) {
                var $this = $(this);
                var prevClasses = this.getAttribute('class');
                var classNames = $.isFunction(n) ? n(i, prevClasses) : n.toString();
                $.each(classNames.split(/\s+/), function(index, className) {
                    if( $this.hasClass(className) ) {
                        func.call( $this, className );
                        $this.trigger('classRemoved', className);
                    }
                });
                prevClasses != this.getAttribute('class') && $this.trigger('classChanged');
            });
            return this;
        }
    })($.fn.removeClass);
    

使用这些替换函数,您可以通过检查回调函数的参数来处理通过classChanged更改的任何类或添加或删除的特定类:

$(document).on('classAdded', '#myElement', function(event, className) {
    if(className == "something") { /* do something */ }
});

答案 2 :(得分:7)

使用trigger解雇您自己的活动。什么时候更改类添加触发器名称

<强> JS Fiddle DEMO

$("#main").on('click', function () {
    $("#chld").addClass("bgcolorRed").trigger("cssFontSet");
});

$('#chld').on('cssFontSet', function () {

    alert("Red bg set ");
});

<强> Learn jQuery: Simple and easy jQuery tutorials blog

答案 3 :(得分:2)

你可以使用这样的东西:

$(this).addClass('someClass');

$(Selector).trigger('ClassChanged')

$(otherSelector).bind('ClassChanged', data, function(){//stuff });

但是,否则,没有,当类发生更改时,没有预定义函数来触发事件。

详细了解触发器here

相关问题