我有一个jQuery代码,它可以根据另一个元素的单击来显示或隐藏菜单。现在我的问题是,如果连续单击,如何使相同的div按钮切换显示和隐藏?
$(document).mouseup(function (e)
{
var container = new Array();
container.push($('#item_1'));
container.push($('#item_2'));
$.each(container, function(key, value) {
if (!$(value).is(e.target) // if the target of the click isn't the container...
&& $(value).has(e.target).length === 0) // ... nor a descendant of the container
{
$(value).hide();
}
});
});
.item_1 {
width: 50px;
height: 50px;
background: blue;
}
.item_2 {
width: 50px;
height: 50px;
background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="$('#item_1').toggle();">Open 1</button>
<label id="item_1" class="item_1">Text 1</label>
<button onclick="$('#item_2').toggle();">Open 2</button>
<label id="item_2" class="item_2">Text 2</label>
预期:再次单击按钮(它是a href
)时关闭MENU
实际:单击相同的a href
仅隐藏菜单。
答案 0 :(得分:2)
$(document).on('mouseup', function (e) {
var $items = $('.item');
var $target = $('#'+ $(e.target).data('target'));
$items.not($target).hide();
$target.toggle();
});
.item_1 {
width: 50px;
height: 50px;
background: blue;
}
.item_2 {
width: 50px;
height: 50px;
background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button data-target="item_1">Open 1</button>
<label id="item_1" class="item item_1">Text 1</label>
<button data-target="item_2">Open 2</button>
<label id="item_2" class="item item_2">Text 2</label>