将课程添加到<a href=""> if nested ul

时间:2017-12-12 10:10:24

标签: jquery

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> .

1 个答案:

答案 0 :(得分:2)

@DCI STUDIOS LTD 你太接近正确的解决方案了。您只是错过了检查第一个链接,然后将类添加到该链接

如下所示: -

df.columns

工作片段: -

&#13;
&#13;
$('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;
&#13;
&#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>

工作代码段: -

&#13;
&#13;
$('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;
&#13;
&#13;