开发者

Adding and Removing an active class

I know this should be simple and has been covered a million times already but I just can;t seem to get it to work.

It's your basic script that makes the last link you clicked in a list become the 'active' link my adding the 'active' class to it.

HTML

<ul id="projectsList">
            <li><a href="#" class="activeProject" id="portoftyne">Port of Tyne</a></li>
            <li><a href="#" id="eaga">Eaga</a></li>
            <li><a href="#" id="gong">Gong</a></li>
            <li><a href="#" id="nufc">NUFC</a></li>
        </ul>

j开发者_运维知识库Query

    $(document).ready(function() {
    $('#projectsList a').click(function(){
         $('.activeProject').removeClass('activeProject')
         $(this).addClass("activeProject");
    });
});

Should work, doesn't at all.

EDIT Nothing wrong with this code, it works fine. There was a section of code above it in the document that was preventing it from working.


I strongly suggest using a variable to hold reference to activeProject. In case you have large pages this would save a lot on the processing as searching DOM can be expensive. It will also make it less prone to problems like the one you're having (selecting the wrong element).

$(document).ready(function() {
        var active = $('#projectsList a.activeProject');
        $('#projectsList a').click(function() {
            if(active) $(active).removeClass('activeProject');
            $(this).addClass("activeProject");
            active=this;
        });
    });


i don't see any problem there.

look: http://jsfiddle.net/JqMK8/

it is working.

the mistake must be somewhere else


Try being more specific with the selector:

$(document).ready(function() {
    $('#projectsList li a').click(function(){
         $('.activeProject').removeClass('activeProject')
         $(this).addClass("activeProject");
    });
});

I'm not sure what's wrong. This code works for other people...


I try it and it works, nothing wrong in your code :

DEMO


Perhaps the ID #projectsList is changed by your output processor? Could happen in .NET or certain Java frameworks.

Try to assign the class .projectsList instead and see if it works.

I could also recommend the practice of Event delegation instead:

$('.projectsList').click(function(evt){
  if ( evt.target.nodeName == 'A' ) {
    var elm = $(evt.target);
    if ( elm.hasClass('activeProject') ) { return; }
    $('.activeProject').removeClass('activeProject');
    $(evt.target).addClass('activeProject');
  }
});

(Simplified and quick written)

UPDATE Sam, I recommend JavaScript Lint if you haven't tried it. Using it online or in your editor(there is bundles and plugins for it) will let you easily spot errors and warnings in your JavaScript code.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜