jquery - jQuery在每个循环中添加元素
问题描述
在我尝试为每个包含特定类的元素添加一个切换按钮时,我对 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>');
在正确的位置。
解决方案
如果我理解正确,您正在尝试添加一个切换按钮,每个按钮<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
推荐阅读
- c++ - 高精度线程同步
- html - 在css中裁剪视频的底部
- vba - 当特定范围内的值 = 同一张表中另一个范围内的值时,则
- javascript - 在 Node.js 中打印年份的最短方法?
- python - 如何在 for 循环中访问我的类中的数组元素
- javascript - 使用 Google Diff Match Patch 获取差异的第一行和第一列?
- php - 在 Laravel 5.7 中使用 nusoap_client 检索 28,000 条记录数据时分配内存
- arrays - 为循环中的每次迭代重置数组
- html - CSS 不适用于使用 @media 的较小页面尺寸
- javascript - 我的异步回调处理是否安全实施?(javascript)