我尝试使用的 JavaScript 代码有问题。我试图调用一个函数来设置事件处理程序,并在该事件处理程序中在调用事件时将其删除。在这个特定的实例中,我尝试在需要输入时添加一个事件处理程序,然后将回调传递给该函数,并在输入准备好时运行代码。同样在这个阶段,我尝试将其删除,以便回调不会被多次触发,但这似乎存在问题。这是代码:
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
你应该明白我的意思。
最佳答案
我看到你的问题..你在代码中引用的“this”不在正确的范围内..
只需这样做:
function display() {
var ref = this;
}
现在替换这些:
this.removeKeyhandler();
这样:
ref.removeKeyhandler();
另外,在删除函数中将其更改为:
$(document).off("keydown");
祝你好运!
关于Javascript 删除 jQuery 事件并获取用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26203224/