开发者

On div hover with some class, find the last class and add class to a link element with the same last class. How in jQuery?

开发者 https://www.devze.com 2023-04-10 06:37 出处:网络
How to add a class to an element(link) when hovering a div with the last class? Here is what I mean: I have this code:

How to add a class to an element(link) when hovering a div with the last class? Here is what I mean:

I have this code:

<a href="http://google.com" class="menu nice menu-2">Google</a>
<a 开发者_开发技巧href="http://yahoo.com" class="menu nice menu-10">Yahoo</a>
<a href="http://facebook.com" class="menu nice menu-20">Facebook</a>

. . .

<div class="pretty fixed menu-20">Some text here</div>

IMPORTANT! I do not know the name of div class. I only know that it will be always the last one! So when I have classes like pretty, fixed and menu-20, I need menu-20.

Now, I have to find the last class of the div and somehow find the same class in link element and add class to that link element e.g. "awesome" so it look like:

<a href="http://google.com" class="menu nice menu-2">Google</a>
<a href="http://yahoo.com" class="menu nice menu-10">Yahoo</a>
<a href="http://facebook.com" class="menu nice menu-20 awesome">Facebook</a>

.

How to do this?

Thanks in advance.


Classes are just another attribute, which means you can extract them using attr() and manipulate them as strings:

$('div').hover(function() { // mouseover
    var arrClasses = $(this).attr("class").split(" ");
    var strLastClass = arrClasses[arrClasses.length-1];
    $('a.'+strLastClass).addClass("awesome");
}, function() {  // mouseout
    $('a').removeClass("awesome"); // easier to just remove it everywhere
});


You could do;

function getNameOfLastClass(el){

   var classNames=$(el).attr('class');
   var classes = classNames.split(' ');
   var lastClass = classes.pop();
    return lastClass;
}

$('div').hover(function(){
   var last = getNameOfLastClass(this);
   console.log(last);
    $('a').each(function(){
         var lastA = getNameOfLastClass(this);
        if (lastA === last){
            $(this).addClass('awesome');
        }
    });

}
 function(){
        $('a').removeClass('awesome');
 });

fiddle here http://jsfiddle.net/JqMfZ/1/


Try this

 $('div').hover(function(){
      var myClass =$(this).attr('class').split(' ')[$(this).attr('class').split(' ').length - 1];
       $('a.'+myClass ).addClass("awesome");
    })
0

精彩评论

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

关注公众号