简体   繁体   中英

JQuery - How to add class to certain span if href equals something

I have a menu on a page. I want to add the class username to the my username span, that has an a href ; that equals ?m=user_admin&p=edit_user&user_id=1 .

Keep in mind that I want it to add this class, no matter what the username is! because the username will change all the time. How can I do it?

Example of the Menu

 <div class="menu"> <ul> <li><a class="user_menu_link_selected" href="#"><span>Dashboard</span></a></li> <li><a class="user_menu_link" href="#"><span>Monitor</span></a><li> <li><a class="user_menu_link" href="#"><span>Admin</span></a></li> <li><a class="user_menu_link" href="#"><span>FTP</span></a></li> <li><a class="user_menu_link" href="?m=user_admin&p=edit_user&user_id=1"><span>my username</span></a></li> </ul> </div> 

I tried this JS code but it added the class to all the spans. I only want it added on the my username span because the href equals ?m=user_admin&p=edit_user&user_id=1 .

  $('ul a').each( function(){ if($(this).attr('href')=="?m=user_admin&p=edit_user&user_id=1"){ $('.menu > ul > li > a > span').addClass("username"); } }); 

$('ul a').each(
    function(){
        if($(this).attr('href')=="?m=user_admin&p=edit_user&user_id=1"){
            $(this).find('span').addClass("username");
        }
});

The following line should refer to this :

$('.menu > ul > li > a > span').addClass("username");

Probably

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

use CSS here is the documentation it will select all the span whose parent a has the link

a[href='?m=user_admin&p=edit_user&user_id=1'] span {
  color:Red
}

demo - http://jsfiddle.net/zq0fs7om/

Try this..

  $('ul li a').each( function(index){ if($(this).attr('href')=="?m=user_admin&p=edit_user&user_id=1"){ $(this).children('span').addClass("username"); } }); 

You can check out the jsfiddle here: http://jsfiddle.net/ow1478rd/

here's the gist of the code:

$('ul > li > a').each(function(){
    if($(this).attr('href')=="?m=user_admin&p=edit_user&user_id=1"){
        $(this).closest("li").find("span").addClass("username");
    }
}); 

Basically the thing to note here is "closest" will basically search UP the DOM, and then "find" will search DOWN the DOM. so with your structure you're going up to the closest list element, and then finding the span inside of it to change the CSS. Hope this helps man.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM