开发者

jQuery functions

I'm trying to remove a class from a HTML tag along with adding a new one and also doing some other magic.

Right now I just have a procedure style coding going on... which I know there's another way of doing it. Like creating a function within another function? I'm not sure what it's called and sometimes when trying to do it, it never worked so I开发者_运维百科 went down procedure style type but I figured I post on here and maybe someone can explain to me on how jQuery works? Right now I have like

$(this).removeClass("theClass");
$(this).addClass("theClass");
$(this).slideDown();

I think I can do something like

$(this).removeClass("theClass", function(){
  // other goodness?
});

Thanks everyone. Sorry if i don't make sense.


I think what you're looking for is call chaining - since .removeClass returns a jQuery object itself, you can call .addClass directly on the returned object, like so:

$(this).removeClass("classA").addClass("classB").slideDown();

Some animations also take functions called callbacks as arguments; these functions specify actions to take after the animation is complete. For example:

$(this).fadeOut("slow", function() {
    // Callback function - called after fade is done
    alert("fade complete");
});


You can do this:

$(this).removeClass("theClass").addClass("theNewClass").slideDown();

You can read more about chaining here.


It depends what you want to achieve. If you just want to do these three operations in sequence you can use chaining as mentioned above. In case you want to execute some of operations when slideDown finishes its animation, you can do it like this:

var that = this;
$(this).removeClass("theClass").sildeDown(function() {
  $(that).addClass("theClass");
});

It will remove the class from element, slide it down and after slide is finished it will add the class again. Use of that variable is necessary as inside the callback anonymous function this keyword can refer to something else than your DOM element. Hope that helps!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜