简体   繁体   English

jQuery导航菜单

[英]Jquery navigation menu

The above code does not work properly. 上面的代码无法正常工作。 I need to implement a simple menu with sub-menu items using Jquery. 我需要使用Jquery实现一个带有子菜单项的简单菜单。 When I open the web-page, I see the content of all menus and submenus all together (like a stack). 当我打开网页时,可以看到所有菜单和子菜单的内容(如堆栈)。 I need to improve JavaScript shown below in order to properly assign the content to menu items. 我需要改进下面显示的JavaScript,以便将内容正确分配给菜单项。 So, when I click "menu2",there should be the content of DIV id = "menu2". 因此,当我单击“菜单2”时,应该有DIV id =“菜单2”的内容。 Now I see all content on one page. 现在,我可以在一页上看到所有内容。

<!-- Start css3menu.com BODY section -->
<ul id="css3menu1">
<li class="topfirst"><a class="pressed" href="#menu1" style="height:40px;line-height:40px;"><span>menu1</span></a>
<ul class = "menu">
<li><a href="#submenu11">submenu11</a></li>
<li><a href="#submenu12">submenu12</a></li>
<li><a href="#submenu13">submenu13</a></li>
<li><a href="#submenu14">submenu14</a></li>
</ul></li>
<li class="menu"><a href="#menu2" style="height:40px;line-height:40px;">menu2</a></li>
<li class="menu"><a href="#menu3" style="height:40px;line-height:40px;">menu3</a></li>
<li class="toplast"><a href="#menu4" style="height:40px;line-height:40px;">menu4</a></li>
</ul>
<!-- End css3menu.com BODY section -->

<script>
$('ul.menu').each(function() {
var $active, $content, $links = $(this).find('a');
$active = $links.first().addClass('active');
$content = $($active.attr('href'));
$links.not(':first').each(function() {
$($(this).attr('href')).hide();
});

$(this).on('click', 'a', function(e) {
$active.removeClass('active');
$content.hide();
$active = $(this);
$content = $($(this).attr('href'));
$active.addClass('active');
$content.show();
e.preventDefault();
});
});
</script>

This line has an issue 这行有问题

$content = $($active.attr('href'));

There is no item with that ID... ($content is length 0) 没有具有该ID的项目...($ content的长度为0)

eg 例如

  1. you press a link with href="#menu1" 您按下带有href="#menu1"的链接
  2. $active.attr('href') equals to #menu1 $active.attr('href')等于#menu1
  3. which translates to $content = $("#menu1"); 转换为$content = $("#menu1");
  4. there is no element on the page with ID "menu1" 页面上没有ID为“ menu1”的元素

In jQuery a selector with a hash (#) means - find an element with the id after the hash sign 在jQuery中,带有散列(#)的选择器意味着-在散列符号后找到具有ID的元素

So #menu1 means the same (almost) as document.getElementById("menu1") 因此, #menu1含义(几乎)与document.getElementById("menu1")

However there is no element with that ID (or any id that is equal to the href values) 但是,没有具有该ID(或任何等于href值的ID)的元素

It might not be the last issue, but this is the next stop in the attempt to make it work... 它可能不是最后一个问题,但这是尝试使其工作的下一站...

See in jsFiddle 参见jsFiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM