2016-07-04 56 views
1

我從某處借用此代碼以從一個引導模式切換到另一個模式。切換後,我想關閉處理程序,以便每次只關閉第一個模式時都不會切換。我的問題是,一旦使用了模式切換功能,我不知道如何關閉特定事件處理程序,而不關閉在特定模式關閉時執行的其他事件(在其他位置完成)時如何關閉。有什麼建議麼?使用jquery刪除一個事件處理程序「.off」

//switch modals 
function switchModals(fromModal, toModal) { 
    $(fromModal).on('hidden.bs.modal', function (e) { 
     $(toModal).modal('show'); 
     //clear this function so it doesn't show up if they exit the window again 
     $(fromModal).off('hidden.bs.modal'); 
    }); 
    $(fromModal).modal('hide'); 
} 

回答

0

我找到了解決辦法。我只需要爲處理程序提供一個函數特有的名稱空間。然後我通過它的命名空間在「.off()」方法中解除綁定。我選擇了「switch」作爲命名空間。

//switch modals 
function switchModals(fromModal, toModal) { 
    $(fromModal).on('hidden.bs.modal.switch', function (e) { 
     $(toModal).modal('show'); 
     //clear this function so it doesn't show up if they exit the window again 
     $(fromModal).off('.switch'); 
    }); 
    $(fromModal).modal('hide'); 
} 
1

你需要把該行的switchModals外

$(<FromModalId>).modal('hide'); 
0

嘗試使用this代替fromModalhidden.bs.modal回調,例如內

//switch modals 
function switchModals(fromModal, toModal) { 
    $(fromModal).on('hidden.bs.modal', function (e) { 
     $(toModal).modal('show'); 
     //clear this function so it doesn't show up if they exit the window again 
     $(this).off('hidden.bs.modal'); 
    }); 
    $(fromModal).modal('hide'); 
} 
+0

這沒有奏效。我認爲它需要在.off()的某處指定,但我不知道如何。 – Quin

+0

你可以發佈你的完整代碼,或鏈接到你的網頁? –

0

請嘗試以下方法模態之間切換:

var el = fromModal+','+toModal; 
    $(el).on('hidden.bs.modal', function (e) { 
     $(el).not(this).modal('show'); 
     $(this).modal('hide'); 
    });