简体   繁体   中英

How to increase Jquery variable in each loop

I have a category color function in functions.php file and I am assigning category color for every li element with this code:

$i = 0;
$color = get_term_meta( $menu_item->object_id, '_category_color', true );
$color = ( ! empty( $color ) ) ? "#{$color}" : '#fff';
$menu_list .= "\t\t\t\t\t". '<li id="'.$i .'"style="border-left:5px solid '.$color .';">
<a href="'. $url .'">'. $title .'</a></li>' ."\n";
$i++;

And I am trying to get every li's border-left-color and assign them as a background to that div but in this jquery code, $i is stopping in 1 . How can I make this as a loop for every li?

$(document).ready(function(){
$i = 0;
var $c=$('.side-category ul li#'+$i).css("border-left-color");
$('.side-category ul li#'+$i).css("background", $c);
$i++;
});

Thank you for reading it!

Replace the code within document.ready with this :

$('.side-category ul li').each(function(){
    $(this).css("background", $(this).css("border-left-color"));
})

There is no need to add $i , jQuery has each function , so you can directly use that.

The each function will go through each li within .side-category ul

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