【发布时间】:2019-11-07 12:24:23
【问题描述】:
在尝试为每个包含特定类的元素添加切换按钮时,我对 jQuery 感到有些头疼。
当我使用 jQuery 的 .each( 时,我希望在循环中添加我的标识符类。
但不知何故,它不断将我的html代码循环附加到每个li而不是li.has-children
这是我当前的代码:
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
$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);
//last attempt before ask on SO
if( $(this).hasClass('has-children level-'+level) ){
$( 'li.has-children span a' ).after( '<span class="sub-menu-toggle"></span>');
}
// repeat the process for the sublist, but with the level one higher
// = recursive function call
addLevelClass($sublist, level+1);
}
});
}
// call the function to add level classes on the upper most ul
addLevelClass($('.header-mobile-menu'), 0);
//$( 'li.has-children span a' ).after( '<span class="sub-menu-toggle"></span>');//Adds toggle buttons everywhere
所以我们的想法是:
$( 'li.has-children span a' ).after( '<span class="sub-menu-toggle"></span>');
在正确的位置。
【问题讨论】:
-
你能张贴标记吗?你也不需要
if( $(this).hasClass('has-children level-'+level) ),因为它总是正确的 -
@SeanT ,感谢您的帮助尝试(小提琴很痛苦,答案来得更快)。我做了很多尝试,例如:
find('a'),但应该是find('span:first')。我们不断学习。