[英]Stop propagation for a specific handler
假設我有自定義下拉列表()。 單擊按鈕時,我想調出菜單,當用戶點擊菜單外部時,我希望它關閉。 所以我這樣做:
$(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-element就會立即調用它。
假設你有一個你的投影選擇器,(讓我們說“ .dropdown
”),我會嘗試使用' .not()
'
$('.dropdown').mousedown(dropDownMouseDown);
$("html").on('mousedown', htmlMouseDown);
function dropDownMouseDown(event) {
event.target.open();
}
function htmlMouseDown(event) {
$('.dropdown').not($(event.target)).close();
}
這里有一個與css類相同的小提琴: http : //jsfiddle.net/eFEL6/4/
使用包含最后一個打開的變量的變量怎么樣? 可能有很多其他方法可以做到這一點,但這是我能想到的一種方式:
var lastOpened = null; // initially nothing is open (unless something is)
然后:
function dropDownMouseDown(event) {
if (lastOpened != null) { // if one is still open
lastOpened.close(); // close it
lastOpened = null; // nothing is open anymore
}
event.target.open();
lastOpened = event.target; // now this one is open
event.stopPropagation();
}
function htmlMouseDown() {
this.close();
lastOpened = null; // nothing is open
}
這應該以一種方式工作,即最后打開的那個在打開一個新的之前總是關閉。
謝謝你的回答。 他們真的很感激。 我確實找到了一種方法,我很滿意。 這是如何做:
$(myDropDown).mousedown(dropDownMouseDown);
$("html").mousedown(myDropDown,htmlMouseDown);//Pass in the dropDown as the data argument, which can then be accessed by doing event.data in the handler
function dropDownMouseDown(event) {
event.target.open();
}
function htmlMouseDown(event) {
if (event.target!=event.data)//event.target is the element that was clicked, event.data is set to the dropdown that this handler was added for. Unless these two elements are the same then we can...
event.data.close();///close the dropdown this handler was added for
}
簡直不敢相信我沒想到。 在我的情況下,雖然打開/關閉的元素具有子元素,因此event.target可以是子元素之一,而不是處理程序附加到的元素。 所以我將我的html-element-handler更改為:
function htmlMouseDown(event) {
var element=event.target;
while (element) {
if (element==event.data)
return;
element=element.parentElement;
}
event.data.hide();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.