开发者

jquery set current class on anchor tags

I currently have this jquery code to set the current class, I am a bit of a novice with jquery and would like to know how to make this cleaner and more compact. It currently works but I would like to know how to do it better.

// add class curre开发者_运维技巧nt
$('.textResizing ul .normal a').click(function () {
    $('.textResizing ul .normal a').addClass('current');
    $('.textResizing ul .medium a').removeClass('current');
    $('.textResizing ul .large a').removeClass('current');
});

$ ('.textResizing ul .medium a').click(function () {
    $('.textResizing ul .medium a').addClass('current');
    $('.textResizing ul .normal a').removeClass('current');
    $('.textResizing ul .large a').removeClass('current');
});

$ ('.textResizing ul .large a').click(function () {
    $('.textResizing ul .large a').addClass('current');
        $('.textResizing ul .normal a').removeClass('current');
    $('.textResizing ul .medium a').removeClass('current');
});


Not sure what your html looks like but something like this? :

$('.textResizing ul a').click(function () {
    $('.textResizing ul a').removeClass('current');
    $(this).addClass('current');
});


Well, firs of all you can cache selectors. It’s the easiest and the most useful optimization in jq because each time you use seletors, jq needs to parse dom to find elements. So:

// add class current
var na = $('.textResizing ul .normal a'),
    ma = $('.textResizing ul .medium a'),
    la = $('.textResizing ul .large a');

na.click(function () {
   this.addClass('current');
   ma.removeClass('current');
   la.removeClass('current');
});

ma.click(function () {
   this.addClass('current');
   na.removeClass('current');
   la.removeClass('current');
});

la.click(function () {
   this.addClass('current');
   na.removeClass('current');
   ma.removeClass('current');
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜