2014-10-05 62 views
0

我嘗試使用的JavaScript代碼存在問題。我試圖調用一個函數來設置一個事件處理程序,並在該事件處理程序中也調用該事件時將其刪除。在這個特定的實例中,我試圖在需要輸入時添加一個事件處理函數,然後將回調函數傳遞給函數,並在輸入準備就緒時運行代碼。同樣在這個階段,我嘗試刪除它,所以回調不會觸發多次,但似乎有這個問題。下面是代碼:JavaScript刪除jQuery事件並獲取用戶輸入

this.validateInput = function(NaN, callback) { 

    // Wait for the user to click submit or press 
    // enter, then if the input is a valid number 
    // return true. If it is not valid return false 
    $(document).keydown(function(e) { 

     // If the enter key is pressed, if the box is focused and if 
     if (e.which == 13 && $("#inputBox").is(":focus")) { 

      // Print the user's input regardless of whether it is a 
      // number or not. 
      var newOutput = $("#inputBox").val() 
      $("#output").append(newOutput + "<br>"); 
      // If the user wants the input to be a number then 
      // the program checks if the input is not numerical. 
      if (NaN && !isNaN($("#inputBox").val())) { 

       // Get input from screen 
       var newInput = $("#inputBox").val(); 

       // Remove this handler 
       this.removeKeyhandler(); 

       // Call the code passed to the function 
       callback(newInput); 

       // Return from the function. 
       return; 

      // This checks if the user wants non-number input 
      // and runs the following code IF the input is not numerical 
      } else if (!NaN && isNaN($("#inputBox").val())) { 

       // Get input from screen 
       var newInput = $("#inputBox").val(); 

       // Remove this handler 
       this.removeKeyhandler(); 

       // Call the code passed to the function 
       callback(newInput); 

       // Return from the function 
       return; 
      } 
     } 
    }); 


} 

僅供參考,#inputBox是一個輸入框,#output<div>我試圖輸出,並且只需removeKeyHandler()包含的代碼$(document).off("keydown", document);。如果你想看到完整的文件/項目,它是here

似乎沒有工作的唯一事情是事件處理程序沒有刪除,它會一直保持多次添加輸入。如果你下載project並打開index.html你應該明白我的意思。

+0

如果你想keydown事件只觸發一次,爲什麼不使用$(document).one('keydown',function(){....})? – webkit 2014-10-05 14:02:41

+0

@webkit問題在於它會在你想按下某個按鍵時觸發,但我只希望只有在按下輸入鍵時才能將其移除。 – HexCoder 2014-10-05 14:10:04

+0

是的在這種情況下..你做了什麼是對的,但我已經在下面的答案中發現了你的問題.. – webkit 2014-10-05 14:11:56

回答

1

我看到你的問題..你的「這個」你指的是你的代碼是不正確的範圍..

簡單的做到這些:

function display() { 
    var ref = this; 

} 

現在更換這些:

this.removeKeyhandler(); 

與此:

ref.removeKeyhandler(); 

同樣在您的移除功能中將其更改爲:

$(document).off("keydown"); 

祝你好運!

+0

它的工作!謝謝。我仍然有點不確定爲什麼我的代碼錯了,你能解釋一下嗎?你不允許在另一個對象函數中調用其他對象函數嗎? – HexCoder 2014-10-05 14:21:03

+0

'範圍'有很多信息..谷歌了'javascript範圍'//基本上JavaScript中的'this'關鍵字指的是當前上下文中的對象,在你的情況下#document ..我建議你研究這個問題,因爲它是高級javascript的關鍵知識;) – webkit 2014-10-05 14:28:24

+0

啊,我明白你的意思了。我完全忘了事件處理程序的範圍:) – HexCoder 2014-10-05 14:35:24