JQuery override function

I have a huge application, where addClassand removeClass jquery is used in many places. I want to do some work on which element is changed by a class based on which class is added / removed. A longer route would be to add a piece of code to the application after addClassand removeClass, but I was thinking if I could override these jquery functions somehow, then my life would be much easier. I tried the code below.

var oAddClass = jQuery.fn.addClass;
jQuery.fn.addClass = function (arg) {
    alert(this);
    alert(arg);

    // Now go back to jQuery original size()
    return oAddClass.apply(this, arg);
};

But getting the error “ Function .prototype.apply: argument is not an object ” inreturn oAddClass.apply(this, arg);

Can someone help me?

+4
source share
4

.apply .

return oAddClass.apply(this, arguments);
+1

- .apply(), .apply() . arguments:

  var args = [];
  for (var i = 0; i < arguments.length; ++i) args[i] = arguments[i];
  oAddClass.apply(this, args);

arguments - , . , , .

+3

: jQuery .addClass, , - , .

, addClass / removeClass.

+1

, jQuery.addClass , , .call .

: jQuery , , addClass ( ).

(function () {
  var oAddClass = jQuery.fn.addClass;
  jQuery.fn.addClass = function(arg) {
    return oAddClass.call(this, arg);
  };
}());

$('#foo').addClass('foo bar');

$('span').addClass(function(index) {
  if (index == 0) {
    return 'bar';
  }
  return 'foo';
});

$('button').on('click', function () {
    $('#foo').toggleClass('foo');
});
.foo {
  background-color: green;
}
.bar {
  color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="foo">Hello World</div>
<span>Span 1</span>
<br />
<span>Span 2</span>
<br />
<button>Toggle .foo on the div</button>
Hide result
+1

All Articles