Auf welches Element wird geklickt? Nicht die gesamte #nav-mobile
, sondern die a
s innen. Sie möchten #nav-mobile a
als Ihren Selektor.
Nun, wo sind die ul
s in Bezug auf ihre entsprechenden a
(in der Callback-Funktion als $(this)
bezeichnet)? Sie sind unmittelbare Geschwister, also $(this).next('ul')
ist Ihre beste Wette.
Um alle anderen Menüoptionen zu schließen, speichern Sie die Variable ul
in einer Variablen und verwenden Sie .not()
, um die anderen ul
s auszuwählen.
Ihr Code sollte jetzt so aussehen.
$(document).ready(function() {
$('#nav-mobile ul').hide();
$('#nav-mobile a').click(function(e) {
e.preventDefault();
var $menuItem = $(this).next('ul');
$menuItem.slideToggle();
$('#nav-mobile ul').not($menuItem).slideUp();
});
});
#tab1, #tab2, #tab3{
background-color:grey;
color:white;
padding:5px 10px;
display:block;
width:100px;
border-bottom:1px solid;
}
#tab1:hover, #tab2:hover, #tab3:hover{
background-color:darkgrey;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="nav-mobile">
<a href="#" id="tab1">Products</a>
<ul style="display: none;">
<li><a href="index.php">Home</a></li>
<li><a href="#">Why Us</a></li>
<li><a href="#">Our Work</a></li>
</ul>
<a href="#" id="tab2">About</a>
<ul style="display: none;">
<li><a href="#">Our Equipment</a></li>
<li><a href="#">Video Production</a></li>
</ul>
<a href="#" id="tab3">Contact</a>
<ul style="display: none;">
<li id="last-child"><a href="#">Contact</a></li>
<li id="last-child"><a href="#">Social Media</a></li>
</ul>
</div>
wäre es hilfreich, den Code als Code-Schnipsel in Ihrer Frage aufzunehmen. – darrylyeo