开发者

How to remove a css class with jquery?

I am adding a css class to some asp buttons on mouseenter and removing that class on mouseleave but i don't see the effect of new class the class which i added on mouse enter is still there.

I m doing something like:

 <script src="jquery-1.6.2.js" type="text/javascript"></script>
    <script type="text/javascript">

        $(document).ready(function () {

            // mouse hover
            $("[id^='MangoPager_btn']").mouseenter(mouseenterfunction);
            // mouse leave
            $("[id^='MangoPager_btn']").mouseleave(mouseleavefunction);

        });

        function mouseleavefunction() {

            $(this).removeClass("pagerbtnHover");
            $(this).addClass("buttonclass");        }

        function mouseenterfunction() {

            $(this).addClass("pagerbtnMouseEnter");
 开发者_高级运维       }

    </script>

on mouse leave i want to remove pagerbtnMouseEnter class and want to attach buttonclass.


You are not removing the same class you are adding...

$(this).addClass("pagerbtnMouseEnter");
$(this).removeClass("pagerbtnHover");


You're adding a different class than you're removing:

$(this).addClass("pagerbtnMouseEnter");

// should be $(this).removeClass('pagerbtnMouseEnter');
$(this).removeClass("pagerbtnHover");

Make sure both class names match and you shouldn't have a problem.

On another note, you could clean your JavaScript up a bit by using hover() and getting rid of the use of $(document).ready():

$(function(){
    $("[id^='MangoPager_btn']").hover(function(){
        $(this).toggleClass('pagerbtnMouseEnter');
    });
);


$(this).removeClass("pagerbtnHover");

$(this).addClass("pagerbtnMouseEnter");

you are removing the wrong class....


Even simpler: use .hover() with a single argument, and .toggleClass().

$(function ()
{
    $("[id^='MangoPager_btn']").hover(function ()
    {
        $(this).toggleClass('pagerbtnMouseEnter');
    });
});


I would recommend that you make all buttons have the buttonclass class at all times, and have pagerBtnHover override the necessary styles in button class. Get rid of the pagerbtnMouseEnter class. Then, you can do:

function mouseleavefunction() {
    $(this).removeClass("pagerbtnHover");
}

function mouseenterfunction() {
    $(this).addClass("pagerbtnHover");
}


No need to call the jQuery selector twice, you can chain.

$(this).removeClass('pagerbtnMouseEnter').addClass("buttonclass");

Also you should stick that retrieved element to a variable if you want to use it somwhere else, instead of calling the same jQuery function to find it again and again.

var $this = $(this);

// Use $this from here on...
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜