2017-06-29 79 views
1

我有以下一行jquery,它可以響應窗體上任何文本輸入中的任何按鍵事件。然後,它運行一個名爲processPrimarySearch功能:運行函數時使用jquery .on

$('#primarySearch input[type="text"]').on('keyup', this, processPrimarySearch); 

這工作,但我想適應它的keyup忽略標籤按鍵如下所述:Keyup event behavior on tab

我無法工作,如何重新寫這個,因爲我不知道如何通過this之前致電processPrimarySearch。例如,我有以下,但它不工作,我不明白我應該寫,使其工作:

$('#primarySearch input[type="text"]').on({ 

    "keyup": function(e) { 
     if (e.which != 9) { 
      // No reference to 'this'! 
      processPrimarySearch(); 
     } 
    } 
}); 

function processPrimarySearch() { 
    // ... 
} 

回答

3

你的邏輯是正確的差不多,你只需要使用call()來爲該功能提供上下文。試試這個:

$('#primarySearch input[type="text"]').on({ 
    "keyup": function(e) { 
    if (e.which != 9) { 
     processPrimarySearch.call(this); 
    } 
    } 
}); 

function processPrimarySearch() { 
    // ... 
} 
+0

完美地工作。非常感謝。我並不知道'.call()',所以會進一步研究。 – Andy

+0

沒問題,很樂意幫忙。以下是供您參考的文檔:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call –