在网站上我有几个下拉列表'当你按一个加号时会变得可见。我用jQuery做了这个(见下面的代码),但按下按钮时每个dorpdown都会打开。如何才能打开按下按钮的下拉列表(不再为每个按钮编写此代码)?
$('main .menu').click(function() {
if($(this).hasClass('open')) {
$(this).removeClass('open');
$('main .menu').html('+');
$('main .info').slideUp();
}
else {
$(this).addClass('open');
$('main .menu').html('-');
$('main .info').slideDown();
}
});
HTML:
<div id="first">
<img src="images/flexit.jpg" alt="">
<h2>Flexit</h2>
<a href="#" class="menu">+</a>
<div class="info">
<table>
<tr>
<td>Name:</td>
<td>Flexit</td>
</tr>
<tr>
<td>Dimensions:</td>
<td>2000 x 1600 x 1900 mm</td>
</tr>
<tr>
<td>Material(s):</td>
<td>powdercoated steal, redwood</td>
</tr>
<tr>
<td>Weight:</td>
<td>43 kg</td>
</tr>
<tr>
<td>Current location:</td>
<td>Buzzkruit exhibition, Designcenter Winkelhaak Antwerp</td>
</tr>
</table>
</div>
答案 0 :(得分:4)
您需要在菜单前保留加号:
<a href="#" class="menu-trigger">+</a>
<ul class="menu">
<!-- Menu -->
</ul>
<a href="#" class="menu-trigger">+</a>
<ul class="menu">
<!-- Menu -->
</ul>
在jQuery中,你只需要给予加号,你也可以将加号作为减号:
$(".menu-trigger").click(function () {
$(this).next(".menu").toggleClass("open"); // Selects only the next one!
});
点击此处的代码段:
$(function () {
$(".menu-trigger").click(function () {
$(this).next(".menu").toggleClass("open"); // Selects only the next one!
$(this).html($(this).next(".menu").hasClass("open") ? '-' : '+');
return false;
});
});
.menu-trigger {display: block; width: 3em; text-decoration: none;}
.menu {display: none;}
.menu.open {display: block;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<a href="#" class="menu-trigger">+</a>
<ul class="menu">
<li>Menu 1</li>
<li>Menu 1</li>
<li>Menu 1</li>
</ul>
<a href="#" class="menu-trigger">+</a>
<ul class="menu">
<li>Menu 2</li>
<li>Menu 2</li>
<li>Menu 2</li>
</ul>