Javascript 搬入UL并更换LI课程,如果有。有\u儿童课程
如果存在Javascript 搬入UL并更换LI课程,如果有。有\u儿童课程,javascript,jquery,html,Javascript,Jquery,Html,如果存在.has\u children,我需要在UL元素中移动并更改LI和children UL类。请参见此示例: <ul class="nav navbar-nav"> <li class="first current parent">Link1</li> <li class="parent">Link2</li> <li class="has_children parent"><a href
.has\u children
,我需要在UL元素中移动并更改LI和children UL类。请参见此示例:
<ul class="nav navbar-nav">
<li class="first current parent">Link1</li>
<li class="parent">Link2</li>
<li class="has_children parent"><a href="#">Link3</a>
<ul class="dropdown">
<li class="first parent">SubItem1</li>
<li class="last parent">SubItem2</li>
</ul>
</li>
</ul>
我尝试使用以下代码在元素内部移动:
$.each("ul.nav > li"), function(index, element) {
console.log($(this).text());
}
但是没用,有人能给我一些帮助或推动吗?我不确定我是否做对了。但我想我已经很接近了。尝试使用类似以下递归函数的方法:
$(function(){
doIt( $('li', '.nav') );
});
var doIt = function($element){
$e = $element || null;
$e.each(function(){
if( $(this).hasClass('has_children') ){
$(this).attr('class', 'dropdown');
$(this).children().attr('class', 'dropdown-menu dropdown-megamenu').children().each(function(){
$(this).removeAttr('class');
});
}
});
this($e.next());
};
如果我正确理解了问题,您希望更改所有类名,如果是这种情况,而不是使用
(子)选择器,您可以使用后代选择器:
$("ul.nav li").each(function (index, element) {
var $this = $(this),
cls = '';
if ($this.hasClass('current'))
{
cls = 'active';
}
else if ($this.hasClass('has_children'))
{
cls = 'dropdown';
$this.children('.dropdown')
.attr('class', 'dropdown-menu dropdown-megamenu')
.end()
.children('a')
.attr({
'data-close-others': 'true',
'data-hover' : 'dropdown',
'data-toggle' : 'dropdown',
'class' : 'dropdown-toggle'
});
}
$this.attr('class', cls);
});
请注意,我使用了
attr
方法重置类属性的值,如果您想添加/删除某些类名,可以使用addClass
/removeClass
方法 这个简短的代码段有几个语法错误。@undefined您能给我指出正确的方向吗?或者您对几个语法错误的意思是什么
?)
之后的“
应该位于代码的最末尾,以使语法正确。但是,您要做的是迭代字符串中的字符。您可能打算使用该选择器获取元素,在这种情况下,您只需执行$()ul.nav>li”).each(函数(){…})
@cookiemonster是的,我只是在迭代槽名称以测试我是否正确,但我发现我很糟糕。因此,在每次迭代槽名称后,我如何获得每个槽中的元素?我是否应该制作一个用于测试的插入器?非常好,这正是我试图做的,但没有成功。我错过了主代码中的一些内容,它与元素,其中进行了更改。您能看一看,并在
`元素中添加对更改参数的支持吗?@ReynierPM我已经使用end
和attr
方法更新了代码。更聪明的回答是我对使用.find()
和$this
的想法,谢谢您的回复
$("ul.nav li").each(function (index, element) {
var $this = $(this),
cls = '';
if ($this.hasClass('current'))
{
cls = 'active';
}
else if ($this.hasClass('has_children'))
{
cls = 'dropdown';
$this.children('.dropdown')
.attr('class', 'dropdown-menu dropdown-megamenu')
.end()
.children('a')
.attr({
'data-close-others': 'true',
'data-hover' : 'dropdown',
'data-toggle' : 'dropdown',
'class' : 'dropdown-toggle'
});
}
$this.attr('class', cls);
});