2017-08-24 32 views
0

我試圖在處理程序在jquery中執行.on(「click」)事件之前添加確認對話框。這是原文:在.on()事件處理程序之前添加確認對話框檢查

$(this.var_mainSelector).on("click", 
    this.var_acceptOfferSelector, 
    this.onAcceptOffer 
); 

我已經試過:提前

$(this.var_mainSelector).on("click", this.var_acceptOfferSelector, 
    function() { 
     var test = confirm("are u sure?"); 
     if(test) { 
      this.onAcceptOffer 
     } 
    } 

謝謝!

回答

2

差不多;)封閉本身定義了一個新的「this」,所以this.onAcceptOffer不再被定義。

解決方案

1)把它保存在自

var self = this; 
$(this.var_mainSelector).on("click", this.var_acceptOfferSelector, function(evt) { 
    var test = confirm("are u sure?"); 
    if(test) { 
     self.onAcceptOffer.call(this, evt); 
    } 
}); 

2)不要使用function。而是使用()=>

$(this.var_mainSelector).on("click", this.var_acceptOfferSelector, (evt)=>{ 
    var test = confirm("are u sure?"); 
    if(test) { 
     this.onAcceptOffer.call(null, evt); // original "this" (the clicked element) is lost 
    } 
}); 

箭頭功能( 「()=>」)不改變功能

+1

你需要調用'self.onAcceptOffer()' – Barmar

+0

@Barmar已經固定的功能的情況下: ) –

+0

非常感謝你JoshuaK不僅讚賞答案,而且讚賞它背後的解釋和比較解決方案。 對你也是@Barmar – limco

相關問題