[英]Remove class when clicked outside the parent element
In the HTML shown below, I want to display input
after click on "ورود" and hide it when I click outside it's parent <div>
. 在下面显示的HTML中,我想在单击“ورود”后显示input
,而在其父<div>
外部单击时将其隐藏。
HTML HTML
<div id="user-login-top">ورود</div>
<div id="user-login-wrapper" class="">visible
<input type="text" value="name">
</div>
Jquery jQuery的
$(function () {
$("#user-login-top").on("click", function () {
$("#user-login-wrapper").addClass("wide");
});
$(document).on("click", function (e) {
if ($(e.target).is("#user-login-wrapper, #user-login-top") === false) {
$("#user-login-wrapper").removeClass("wide");
}
});
});
Well you have put the logic for all the targets except the text box that is wrapped in user-login-wrapper
, So just add it with your logic and it works 好了,您已经为所有目标添加了逻辑,除了包装在user-login-wrapper
的文本框之外,因此只需将其与逻辑一起添加即可使用
Example: 例:
$(document).on("click", function (e) {
if ($(e.target).is("#user-login-wrapper")==false
&& $(e.target).is('#user-login-top')==false
&& $(e.target).is('#user-login-wrapper *')==false) {
$("#user-login-wrapper").removeClass("wide");
}
});
You can use jQuery closest()
method as follows: 您可以按如下方式使用jQuery closest()
方法:
$(document).on("click", function (e) {
if (e.target.id != "user-login-top" && !$(e.target).closest("#user-login-wrapper").length) {
$("#user-login-wrapper").removeClass("wide");
}
});
Or If you can move #user-login-top
to the parent of input you can simply do: 或者,如果您可以将#user-login-top
移至输入的父级,则只需执行以下操作:
$(document).on("click", function (e) {
if (!$(e.target).closest("#user-login-wrapper").length)
$("#user-login-wrapper").removeClass("wide");
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.