假设我有自定义下拉()。单击按钮时,我想调出菜单,当用户单击菜单外时,我希望它关闭。所以我做这样的事情:

$(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 处理程序中,但是一旦冒泡到达 html 元素,它将立即被调用。

最佳答案

假设你的下拉菜单有一个选择器,(比如“.dropdown”),我会尝试使用“.not()

$('.dropdown').mousedown(dropDownMouseDown);

$("html").on('mousedown', htmlMouseDown);

function dropDownMouseDown(event) {
    event.target.open();
}

function htmlMouseDown(event) {
  $('.dropdown').not($(event.target)).close();
}

这是一个与 css 类相同的想法的 fiddle :
http://jsfiddle.net/eFEL6/4/

关于javascript - 停止传播特定处理程序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16774968/

10-12 07:07