1

I'm working on a drop-down menu, and would like to selectively change the href attribute for certain elements. The menu is made up of two classes, the menuitems and the submenu items. Every menuitem has a corresponding submenu, but some of the submenus contain empty lists. For the menuitems that have an empty submenu list, I want the href to be "#".

<div id="info" class="menuitem"><a href="http://www.asmithspace.net">Info</a><!--start menuitem-->
<div id="infosubmenu" class="submenu"><!--start submenu-->
<ul>
<li><a href="#">Item1</a></li>
<li><a href="#">Item2</a></li>
<li><a href="#">Item3</a></li>
</ul>
</div><!--end submenu-->
</div><!--end menuitem-->
<div id="business" class="menuitem"><a href="http://www.asmithspace.net">Business</a><!--start menuitem-->
<div id="businesssubmenu" class="submenu"><!--start submenu-->
<ul>
<li><a href="#">Item1</a></li>
<li><a href="#">Item2</a></li>
</ul>
</div><!--end submenu-->
</div><!--end menuitem-->
<div id="jobs" class="menuitem"><a href="http://www.asmithspace.net">Jobs</a><!--start menuitem-->
<div id="jobssubmenu" class="submenu">
<ul>
</ul>
</div><!--end submenu-->
</div><!--end menuitem-->

I've tried different variations of this code with $.each loops and regular javascript, but everything I've done either changes all the menuitem hrefs to "#", or doesn't change any of them.

if (!$('.menuitem').children('.submenu').children('ul').children('li').length > 0) {
$('.menuitem').children('a').attr('href', '#'); }

If anyone can show me what I'm doing wrong I'd really appreciate it! My test page can be found here.

4

2 に答える 2

2
$(".menuitem > a").each(function () {
  if ($(this).next('.submenu').find('li').length > 0)
    $(this).attr("href","#");
});

デモ

于 2013-01-15T16:05:25.557 に答える
0

これがあなたが探しているものだと思います:

$('.menuitem')
  .children('.submenu')
  .each(function(index) {
    if($(this).children('ul').children('li').length === 0) {
      $(this).closest('.menuitem').children('a').attr('href', '#');
    }
  });

サブメニューごとに配列の長さをチェックし、ul > liそれが 0 の場合は、最も近い親メニュー項目のリンクの href を変更します。

于 2013-01-15T16:06:19.613 に答える