我在jquery上有自定义下拉列表,我的开放列表点击工作正常,但我需要处理折叠点击按钮并点击正文。
如何处理正文点击事件以折叠我的列表?
HTML
<div class="xn-dropdown">
<span class="select-button xn-select" >
<span>select
</span>
</span>
<div class="select-menu-wrap">
<div class="select-menu-modal">
<div class="select-menu-list">
<div class="select-menu-item">
<a href="#">itemnumber 1</a>
</div>
<div class="select-menu-item">
<a href="#">itemnumber 1</a>
</div>
<div class="select-menu-item">
<a href="#">itemnumber 1</a>
</div>
</div>
</div>
</div>
javascript
$(document).on("click",".select-button",function() {
$(this).toggleClass('select-button').addClass('selected');
$('.select-menu-wrap').show();
});
if(!$(".xn-select").hasClass('select-button')){
$(document).on("click","body",function() {
$('.xn-select').toggleClass('selected').addClass('select-button');
$('.select-menu-wrap').hide();
});
}
和小提琴(现在工作正常!)
答案 0 :(得分:2)
这是一个应该做的修改
$(document).on("click",".select-button",function(event) {
$(this).toggleClass('select-button').addClass('selected');
$('.select-menu-wrap').show();
event.stopPropagation();
});
$(document).on("click","body",function() {
$('.xn-select.selected').removeClass('selected').addClass('select-button').next().hide();
});
您需要阻止.select-button
点击事件冒泡到body
,否则正文点击处理程序将撤消按钮点击处理程序所做的更改
答案 1 :(得分:0)
每次只需点击按钮切换怎么样?
$(document).on("click",".select-button",function() {
$(this).toggleClass('selected');
$('.select-menu-wrap').toggle();
});
答案 2 :(得分:0)
这是我的解决方案;
小提琴:http://jsfiddle.net/qMMcN/5/
只是js的一个函数
var open = false;
$(document).bind("click", function (event) {
event.stopPropagation();
var buttonClicked = $(event.target).hasClass('select-button');
if (!open && buttonClicked) {
$('.select-button').addClass('selected');
$('.select-menu-wrap').show();
open = true;
} else {
$('.select-button').removeClass('selected');
$('.select-menu-wrap').hide()
open = false;
}
});