The above code does not work properly. I need to implement a simple menu with sub-menu items using 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. So, when I click "menu2",there should be the content of DIV id = "menu2". 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)
eg
href="#menu1"
$active.attr('href')
equals to #menu1
$content = $("#menu1");
In jQuery a selector with a hash (#) means - find an element with the id after the hash sign
So #menu1
means the same (almost) as document.getElementById("menu1")
However there is no element with that ID (or any id that is equal to the href values)
It might not be the last issue, but this is the next stop in the attempt to make it work...
See in jsFiddle
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.