jQuery add class to current li and remove prev li when click inside li a

匿名 (未验证) 提交于 2019-12-03 02:05:01

问题:

here is html:

if I press 'a' link it will addClass 'current' to clicked li and remove old li class? this is my try:

$('ul li a').click(function(){   $('ul li').removeClass('current');   ... don't know here (add class to current li) ... });

回答1:

Use .parent('li') or .closest('li') to select the clicked

  • .

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


    回答2:

    Use on('click') if you are using latest version of jquery

    $('ul li a').on('click', function(){     $(this).parent().addClass('current').siblings().removeClass('current'); });

    A fiddle is here.



    回答3:

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

    Hope, this will works for you..



    回答4:

    Rob is right but $('ul li.current').removeClass('current'); didn't work for me. Following code works.

    jQuery('ul li a').click(function()  {  jQuery('ul').children().removeClass('selected'); jQuery(this).closest('li').addClass('selected');

    }



    回答5:

    http://jsfiddle.net/z8DYP/3/



    回答6:

    Just add the the class to this like so...

    $(this).addClass('yourClass');


    回答7:

    Maybe you mean this?

    $('ul li').each(function(){   var t = $(this);   t.find('a').click(function() {     $('ul li').removeClass('current');     t.addClass('current');   }); });


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