gpt4 book ai didi

javascript - 单击外部时隐藏下拉菜单

转载 作者:行者123 更新时间:2023-12-03 06:28:03 25 4
gpt4 key购买 nike

我有一个下拉菜单,里面有复选框。我想当用户点击外部时关闭下拉菜单。

我的代码是:

<form>
<div class="multiselect">
<div class="selectBox" onclick="showCheckboxes()">
<select>
</select>
</div>
<div class="checkboxes" id="checkboxes">
@{
if (ViewBag.DataActiveEmployee == null || ((IEnumerable<MvcApplication1.Models.ActiveUsersList>)ViewBag.DataActiveEmployee).Count() == 0)
{
//@:<h3>No records were processed.</h3>

}
else
{
foreach (var usr in ViewBag.DataActiveEmployee)
{
<label id="userName">@usr.EmployeeName</label>
<input class="checked" type="checkbox" name="search_emp" id="search_emp" value=@usr.EmployeeName>
@:
}
}
}

</div>
</div>

JS

<script>
var expanded = false;
checkboxes.style.display = "none";
function showCheckboxes() {
var checkboxes = document.getElementById("checkboxes");
if (!expanded) {
checkboxes.style.display = "block";
expanded = true;
} else {
checkboxes.style.display = "none";
expanded = false;
}
}

$('multiselect').click(function () {
$("#checkboxes").hide();
});

问题出在 JavaScript 的第二个函数内部,因为当我按下外部时,什么也没有发生。

请帮忙。

最佳答案

尝试使用event.target来处理点击事件:

更新

$(document).on('click', '.multiselect .selectBox', function(e) {
e.stopImmediatePropagation();
$('#checkboxes').show();
});

$('body').on('click', function(e) {
if (e.target.id != 'checkboxes' && $(e.target).closest('#checkboxes').length == 0) {
$('#checkboxes').hide();
}
});
#checkboxes,
.multiselect {
padding:15px;
border:1px solid #d8d8d8;
}

.selectBox { display: inline; }

#checkboxes { display:none }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="multiselect">
<div class="selectBox">
<select>
</select>
</div>
<div class="checkboxes" id="checkboxes">
<label id="userName">Employee 1</label>
<input class="checked" type="checkbox" name="search_emp" id="emp_1" value="val_1">
<label id="userName">Employee 1</label>
<input class="checked" type="checkbox" name="search_emp" id="emp_1" value="val_1">
</div>
</div>

关于javascript - 单击外部时隐藏下拉菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38561315/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com