jQuery addClass foreach ul.sub-menu

2019-08-20 08:02发布

问题:

WordPress does't give ul.sub-menu any unique classes (yet)...

Here is my HTML:

<ul id="menu-primary" class="nav">
 <li>News
   <ul class="sub-menu">
    <li>Local</li>
    <li>Politics</li>
   </ul>
 </li>
 <li>Sports
   <ul class="sub-menu">
    <li>Baseball</li>
    <li>Football</li>
   </ul>
 </li>
 <li>Opinion
   <ul class="sub-menu">
    <li>Forums</li>
    <li>Blogs</li>
   </ul>
 </li>

Using jQuery I can .addClass to the first one only.

 jQuery(document).ready(function($){

     $('ul.sub-menu').addClass (function() {
         return "item-" + $(this).index();
});

The result is this:

<ul id="menu-primary" class="nav">
 <li>News
   <ul class="sub-menu item-1">
    <li>Local</li>
    <li>Politics</li>
   </ul>
 </li>
 <li>Sports
   <ul class="sub-menu">
    <li>Baseball</li>
    <li>Football</li>
   </ul>
 </li>
 <li>Opinion
   <ul class="sub-menu">
    <li>Forums</li>
    <li>Blogs</li>
   </ul>
 </li>

That's great, but how do I assign a unique class to EACH ul.sub-menu?

回答1:

try this code, should do the work.

$(function(){        
     $('ul.sub-menu').addClass (function(idx) {         
         return "item-" + idx;
     });
 });

you can test it here : http://jsfiddle.net/dvdPd/17/



回答2:

Haven't tested it.. but .each() would be the function you need.

$('ul.sub-menu').each(function(index) {
    $(this).addClass("item-" + index);
});