[英]JavaScript - How to run a function when something besides a particular button is clicked?
I have a menu which I want to show/toggle when a button is clicked and hide when some part of the document besides the button is clicked. 我有一个菜单,我想在单击按钮时显示/切换,而在单击按钮以外的文档的某些部分时隐藏。 I've been trying a couple things, as you can see here:
我一直在尝试一些事情,如您在此处看到的:
// $('.dropdown-toggle').click(function()
// {
// $('.dropdown-menu').show();
// });
$(document).click(function()
{
// if ($(this).hasClass('dropdown-toggle'))
// $('.dropdown-menu').toggle();
if ($(this).not('[dropdown-toggle]'))
$('.dropdown-menu').toggle();
});
If I uncomment the top part, for some reason the menu will toggle when a part of the document besides the button is clicked and won't do anything when the button is clicked. 如果我取消注释顶部,则由于某种原因,当单击除按钮之外的文档的一部分时,菜单将切换,而单击按钮时将不执行任何操作。 If I keep that part commented and uncomment the first if statement (even if I replace the 'toggle' with 'show'), the button will toggle no matter what part of the document I click.
如果我保留该部分的注释并取消注释第一个if语句(即使我将“ toggle”替换为“ show”),无论我单击文档的哪个部分,该按钮都将切换。
Edit: I solved part of the problem. 编辑:我解决了部分问题。 It looks like when I uncomment the top part (the click listener for the dropdown-toggle class), the menu shows and then immediately toggles, so it hides.
当我取消注释顶部(下拉式切换类的单击侦听器)时,菜单显示,然后立即切换,因此隐藏。 If I change 'show' to 'hide' I make it so that the menu shows when the button is clicked and toggles otherwise.
如果将“显示”更改为“隐藏”,则会使其显示,以便在单击按钮时显示菜单,否则进行切换。 However, I want to do almost the opposite.
但是,我想做相反的事情。 I want to toggle when the button is clicked and only hide when some other part of the document is clicked.
我想在单击按钮时进行切换,并且仅在单击文档的其他部分时才隐藏。 It seems the "hasClass()" and ".not([])" aren't recognizing the dropdown-toggle as being a class of the thing that's being clicked.
似乎“ hasClass()”和“ .not([])”没有将下拉切换识别为正在单击的事物的一类。
Call .toggle()
within click
handler chained to $(".dropdown-toggle")
; 在链接到
$(".dropdown-toggle")
click
处理程序中调用.toggle()
$(".dropdown-toggle")
; within click
handler chained to $(document)
use .hasClass()
or .is()
to check if event.target
is .dropdown-toggle
, chain .hide()
内
click
处理程序链接到$(document)
使用.hasClass()
或.is()
检查,如果event.target
是.dropdown-toggle
,链.hide()
$(".dropdown-toggle").on("click", function() {
$(this).toggle();
});
$(document).on("click", function(event) {
if (!$(event.target).hasClass(".dropdown-toggle")) $(event.target).hide();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.