jQuery addClass foreach ul.sub-menu

2019-08-20 07:56发布

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?

2条回答
手持菜刀,她持情操
2楼-- · 2019-08-20 08:47

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

$('ul.sub-menu').each(function(index) {
    $(this).addClass("item-" + index);
});
查看更多
你好瞎i
3楼-- · 2019-08-20 08:55

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/

查看更多
登录 后发表回答