开发者

Do jquery function really chain?

I have been told that jquery fu开发者_开发百科nctions can be chained to each other.

So I was wondering if this code:

if (cDiv.hasClass('step-dark-left'))
    cDiv.removeClass('step-dark-left').addClass('step-light-left');

Could be changed by removing the if like so:

cDiv.removeClass('step-dark-left').addClass('step-light-left');

So, if .removeClass fails, then .addClass wont execute?


removeClass() will not fail if the element doesn't expose the step-dark-left class. It will just do nothing and return the jQuery object, therefore addClass() will always be called.

So, you'll have to keep your if statement around, unless you can work the class check in the jQuery selector itself. For instance, if your <div> element has its id attribute set to cDiv:

$("#cDiv.step-dark-left").removeClass("step-dark-left")
                         .addClass("step-light-left");

That way, the jQuery object will be empty if the element doesn't expose the step-dark-left class to begin with, so both removeClass() and addClass() will end up doing nothing in that case.


Yes, the code you write will work as in first example. jQuery is very well written library, and all methods always return the jquery object. So removeClass() method, if it doesn't find a 'step-dark-left' CSS-class, it just would do nothing and return the jquery object so next method in the chain will work.


Yes that will work. If step-dark-left cannot be found it will be just ignored.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜