【发布时间】:2013-05-31 22:40:45
【问题描述】:
假设我有自定义 dropdown()。单击按钮时,我想调出菜单,而当用户单击菜单外时,我希望它关闭。所以我做了这样的事情:
$(myDropDown).mousedown(dropDownMouseDown);
$("html").mousedown(htmlMouseDown,myDropDown);
function dropDownMouseDown(event) {
event.target.open();
event.stopPropagation();//I need this line or else htmlMouseDown will be called immediately causing the dropDown-menu to close right before its opened
}
function htmlMouseDown() {
this.close();
}
嗯,这行得通。但是,如果我添加其中两个呢?如果我单击打开第一个,那么第二个相同,那么两者都将打开,因为 dropDownMouseDown 停止传播,因此 htmlMouseDown 永远不会被第一个调用。 我该如何解决这个问题? 如果我只有这两个,那么为此添加一些逻辑当然很容易,但是如果数量是动态的?另外我可能不想调用 event.stopPropagation() 因为它会对我正在使用的其他库做一些奇怪的事情来监听那个事件? 我也试过把这条线: $("html").mousedown(htmlMouseDown,myDropDown) 在 dropDownMouseDown-handler 内部,但一旦冒泡到达 html 元素,它就会立即被调用。
【问题讨论】:
-
您在这里使用事件委托,捕获
html元素上的每个事件。您可以在捕获事件的位置“更具体”(仅在下拉列表本身上),或者 - 如果您想保留事件委托 - 您可以查看事件的 target_of,以查看它是在哪个元素上触发的。
标签: javascript jquery