Javascript 如何将一个事件绑定到一个元素上?
我使用以下内容作为下拉列表:Javascript 如何将一个事件绑定到一个元素上?,javascript,jquery,Javascript,Jquery,我使用以下内容作为下拉列表: /* recurse through dropdown menus */ $('.dropdown').each(function() { /* track elements: menu, parent */ var dropdown = $(this); var menu = dropdown.next('div.dropdown-menu'), parent = dropdown.parent(); /* function tha
/* recurse through dropdown menus */
$('.dropdown').each(function() {
/* track elements: menu, parent */
var dropdown = $(this);
var menu = dropdown.next('div.dropdown-menu'), parent = dropdown.parent();
/* function that shows THIS menu */
var showMenu = function() {
hideMenu();
showingDropdown = dropdown.addClass('dropdown-active');
showingMenu = menu.show();
showingParent = parent;
};
/* function to show menu when clicked */
dropdown.bind('click',function(e) {
if(e) e.stopPropagation();
if(e) e.preventDefault();
showMenu();
});
/* function to show menu when someone tabs to the box */
dropdown.bind('focus',function() {
showMenu();
});
});
/* hide when clicked outside */
$(document.body).bind('click',function(e) {
if(showingParent) {
var parentElement = showingParent[0];
if(!$.contains(parentElement,e.target) || !parentElement == e.target) {
hideMenu();
}
}
});
注意:
$(document.body).bind('click',函数(e){
问题是,下拉列表在单击或您对其进行制表时打开。但它仅在单击时关闭,而不是在您进行制表时关闭
如何将事件绑定为“跳出”,失去焦点,从而关闭下拉列表
谢谢当您按tab键时,您可以触发外部单击。如下所示:
$('#your_dropdown').bind('keydown', function(e) {
var keyCode = e.keyCode || e.which;
if (keyCode == 9) { //If it's the tab key
$("body").click(); //Force a click outside the dropdown, so it forces a close
}
});
希望这能有所帮助。干杯似乎您正在寻找
模糊
事件?尝试模糊
事件,该事件将在控件失去焦点时触发(即,当用户在控件外单击或使用键盘切换到下一个控件时)
在现有的焦点
绑定之后放置类似的内容:
dropdown.bind('blur',function() {
// whatever tests you want
hideMenu();
});
(您不应该需要当前用于隐藏菜单的单独单击绑定。)
S.S.您也可以考虑<代码> FooSux,它类似于“代码>模糊< /代码>,但它不起作用。< $(文档.Boo.))绑定(“单击OnBurr”,函数(e){@ Apple Prime-尝试<代码>模糊< /代码>,而不是<代码> OnBurr < /C> >(<代码> OnBurr < /C> >,如果您想说“代码>元素.OnBurr=…”,但请注意,
blur
不会冒泡,因此您不想将其绑定到主体:将其绑定到菜单元素,或尝试focusout
。请参阅我的答案。这是JavaScript事件。如果代码中的事件被称为单击和聚焦
,而不是onclick
和onfocus
,它可能只是被称为blur
。说真的吗?有两个事件(blur,focusout
)专门用来告诉你某个元素何时失去焦点,但你却在捕捉按键并寻找标签?