Toggle between two classes in jQuery

天大地大妈咪最大 提交于 2019-11-27 19:41:19

It probably because when you bind those functions there are no results for $(".portlet-header .ui-icon-plusthick"). It doesn't find it. You may add this binding to $(".portlet-header .ui-icon-minusthick").click(function() { ... after adding "ui-icon-plusthick" class.

EDIT: Alternative solution could be:

$(".portlet-header .ui-icon-minusthick").toggle(function() {
        $(this).removeClass("ui-icon-minusthick");
        $(this).addClass("ui-icon-plusthick");
        $(this).parents(".portlet:first").find(".portlet-content").toggle();
    }, function() {
        $(this).removeClass("ui-icon-plusthick");
        $(this).addClass("ui-icon-minusthick");
        $(this).parents(".portlet:first").find(".portlet-content").toggle();
    });

So first click would be first function and second click would be second function.

Bongs

How about

$(YOUR_ELEMENT).live("EVENT_NAME", function() {
    $(".portlet-header").toggleClass("ui-icon-plus").toggleClass("ui-icon-minus");
});

Even more shorter

$(YOUR_ELEMENT).live("EVENT_NAME", function() {
    $(".portlet-header").toggleClass("ui-icon-plus ui-icon-minus");
});

EDIT

As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().


jQuery API reference

George

You can try the below code

$(this).toggleClass('ui-icon-plusthick ui-icon-minusthick');

I wrote this jQuery function, not a plugin, to cycle through any number of classes. Two acts like a toggle. Just put your CSV of classnames in the element's data-classes. Then cycle it with $(selector).cycleClass()

See it in use at www.PluginExamples.com/draggable choose draggable-axis.

(function($){
    $.fn.cycleClass = function(){
        if( !$(this).data("aClasses") ){
            var classes = $(this).attr("data-classes").split(",");
            $(this).data("aClasses", classes);
            $(this).data("classes", classes.join(" "));
            $(this).data("class", classes.length);
        }
        $(this).data("class",($(this).data("class")+1) % $(this).data("aClasses").length);
        $(this).removeClass($(this).data("classes"))
            .addClass( $(this).data("aClasses")[$(this).data("class")] );
        return $(this);
    }
});

Instead of doing all that Javascript, why don't you just modify the ui-icon-plusthick CSS class to show the minus image instead of the plus image?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!