我嘗試使用的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
你應該明白我的意思。
如果你想keydown事件只觸發一次,爲什麼不使用$(document).one('keydown',function(){....})? – webkit 2014-10-05 14:02:41
@webkit問題在於它會在你想按下某個按鍵時觸發,但我只希望只有在按下輸入鍵時才能將其移除。 – HexCoder 2014-10-05 14:10:04
是的在這種情況下..你做了什麼是對的,但我已經在下面的答案中發現了你的問題.. – webkit 2014-10-05 14:11:56