Если я правильно понимаю, вы пытаетесь добавить кнопку переключения с каждым <li>
, у которого есть подменю.
Если это так, я создал скрипку с некоторой общей разметкой, которая может оказаться полезной.
Единственным реальным изменением, которое я сделал, было добавление кнопки переключения, и я удалил рекурсивный вызов самому себе.
Вот обновленный код:
function addLevelClass($parent, level) {
// fetch all the li's that are direct children of the ul
var $children = $parent.children('li');
// loop trough each li
// here I added a check if level is defined, if not set it to 0, this way you don't have to pass it a value unless you want to start it somewhere
var level = (typeof(level) !== 'undefined') ? level : 0;
$children.each(function() {
// get the ul that is a direct child of the li
var $sublist = $(this).children('ul');
// if an ul was found
if ($sublist.length > 0) {
$sublist.addClass('slideable-submenu');
// add a class to the current li indicating there is a sub list
$(this).addClass('has-children level-'+level).find('span:first').append( '<span class="sub-menu-toggle">toggle</span>');
// increment level
level++;
}
});
}
// call the function to add level classes on the upper most ul
addLevelClass($('#parent ul'));
//$( 'li.has-children span a' ).after( '<span class="sub-menu-toggle"></span>');//Adds toggle buttons everywhere