I have the following menu
<ul>
<li><a href="index.html">Main1</a></li>
<li>
<a href="#">Main2</a>
<ul class="sub-menu">
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
</ul>
</li>
</ul>
and im trying, though JS to add a class to the <a href>
if there is a parent menu, so that my menu becomes like this
<ul>
<li><a href="index.html">Main1</a></li>
<li>
<a href="#" class="hassubmenu">Main2</a>
<ul class="sub-menu">
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
</ul>
</li>
</ul>
$("li").has( "ul" ).addClass('contains-sub-menu');
only add the class to the <li>
, how to add it to <a>
.
答案 0 :(得分:2)
@DCI STUDIOS LTD 你太接近正确的解决方案了。您只是错过了检查第一个链接,然后将类添加到该链接
如下所示: -
df.columns
工作片段: -
$('li').has('ul').find('a:first').addClass('hassubmenu');
&#13;
$('li').has('ul').find('a:first').addClass('hassubmenu');
&#13;
.hassubmenu{ /*to show you that code worked*/
color:green;
font-size:20px;
}
&#13;
我之前提供的更好的解决方案(在修改了@A.Wolff建议的内容之后): -
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li> <a href="index.html">Main1</a> </li>
<li> <a href="#">Main2</a>
<ul class="sub-menu">
<li> <a href="#">Link</a> </li>
<li> <a href="#">Link</a> </li>
<li> <a href="#">Link</a> </li>
<li> <a href="#">Link</a> </li>
</ul>
</li>
<li><a href="index.html">Main3</a></li>
<li> <a href="#">Main4</a>
<ul class="sub-menu">
<li> <a href="#">Link</a> </li>
<li> <a href="#">Link</a> </li>
<li> <a href="#">Link</a> </li>
<li> <a href="#">Link</a> </li>
</ul>
</li>
</ul>
工作代码段: -
$('li ul').parent().children('a').addClass('hassubmenu');
&#13;
$('li ul').parent().children('a').addClass('hassubmenu');
&#13;
.hassubmenu{ /*to show you that code worked*/
color:green;
font-size:20px;
}
&#13;