我已经编写了这个绑定到按钮的函数,当单击该按钮切换类以提供下拉列表时。唯一的问题是我在同一页面上有多个具有相同功能的按钮,当点击一个按钮时它们都会触发:
app.bind.DirectionDropdown = function(){
$('.direction-button').bind('click', function(){
$('.direction-dropdown').toggleClass('active');
});
};
这是HTML:
<div class="contact-card">
<div class="contact-directions">
<ul class="contact-directions-items">
<li class="map-pin contact-directions-item"><a href="#"><span class="fa fa-map-marker"></span></a></li>
<li class="contact-directions-item"><p>3700-1 Place Ville Marie</p></li>
<li class="contact-directions-item"><p>Montreal, Quebec</p></li>
<li class="contact-directions-item"><p>H3B 3P4 Canada</p></li>
</ul>
<a href="#" title="#" class="link-button direction-button animate-after">Directions</a>
</div><!-- end .contact-directions -->
</div><!-- end .contact-card -->
<div class="direction-dropdown fade-in">
<h4>Direction on how to get here...</h4>
<a href="#" class="link-button direction-button">Close</a>
<!-- content -->
</div><!-- end .direction-dropdown -->
如何编辑此功能只能在单击的一个按钮上激活,而不是其他按钮?
提前致谢:)
答案 0 :(得分:2)
事件不会传播到其他按钮,但在点击事件中,您再次选择所有按钮。使用this
仅选择已点击的按钮。
app.bind.DirectionDropdown = function(){
$('.direction-button').bind('click', function(){
$('.direction-dropdown').removeClass('active');
$(this).parent().addClass('active');
});
};
或者,如果您希望能够通过再次单击相同按钮来关闭菜单:
app.bind.DirectionDropdown = function(){
$('.direction-button').bind('click', function(){
// Remove the class from all others, excluding the clicked one.
$('.direction-dropdown').not($(this).parent()).removeClass('active');
// Toggle for the clicked one.
$(this).toggleClass('active');
});
};