开发者

How do I remove a CSS class from one anchor and assign it to another using jquery?

开发者 https://www.devze.com 2022-12-24 22:05 出处:网络
Here are my anchors, <a ID=\"lnkbtn0\" class=\"page-numbers\" href=\"#\">1</a> <a ID=\"lnkbtn1\" class=\"page-numbers\" href=\"#\">2</a>

Here are my anchors,

<a ID="lnkbtn0" class="page-numbers" href="#">1</a>
<a ID="lnkbtn1" class="page-numbers" href="#">2</a>
<a ID="lnkbtn2" class="page-numbers" href="#">3</a>
<a ID="lnkbtn3" class="page-numbers" href="#">4</a>

And my click function i am adding a cssclass to show that it is the current anchor

$("a.page-开发者_开发问答numbers").click(function() {
                $(this).addClass('page-numbers current');
    });

What happens is when i click the next anchor the same class has been added to the current and the previous anchor... What can be done to remove the cssclass page-numbers current and assign cssclass page-numbers to the previous/all other anchors without changing the current one....


To avoid a costly run through the entire dom, do this:

$("a.page-numbers").click(function() {
    $(this).addClass('current').siblings().removeClass('current');
});


$("a.page-numbers").click(function() {
    $("a.page-numbers.current").removeClass("current");
    $(this).addClass('current');
});


To follow up on @Danrumb's answer:

A simple solution would be to remove the current class for all (one) a.page-numbers and then add it to the clicked one:

$('a.page-numbers').click(function() {
    $('a.page-numbers').removeClass('current');
    $(this).addClass('current');
});


$("a.page-numbers").click(function() {
                $(this).addClass('current').siblings('a').removeClass('current');
    });

would also be a possibility, even if actually don't like it.


The 'class' page-numbers class is actually 2 classes: page-numbers and current.

To add a class, you simply need

$(this).addClass('page-numbers');

To remove the current class, you would use:

$(this).removeClass('current');

See the docs for more information.


Perhaps something like this:

   $("a.page-numbers").click(function() {
                    $(this).addClass('current').prev('a').removeClass('current');
        });

This is assumes the previous element has current as a class.

Even better would be to do a two stage thing when you click:

1) loop through all the anchor tags and remove the current class from all of them 2) set the current element to have class current.

These means you can click on any of them and it should work


<a ID="lnkbtn0" class="page-numbers" href="#">1</a>
<a ID="lnkbtn1" class="page-numbers" href="#">2</a>
<a ID="lnkbtn2" class="page-numbers" href="#">3</a>
<a ID="lnkbtn3" class="page-numbers" href="#">4</a>

$("a.page-numbers").click(function() {
    $('a.page-numbers.current').removeClass('current');
    $(this).addClass('current');
});

You don't need to keep adding page-numbers, as it's already been added.

0

精彩评论

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