Javascript 删除 jQuery 事件并获取用户输入

标签 javascript jquery callback jquery-callback

我尝试使用的 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/

相关文章:

javascript - 如何统计pinterest的 'Pin it'按钮的点击次数?

javascript - onClick 能够填充模式并提交表单

javascript - 在同一页面上同时使用 highcharts 和 highstock

javascript - 在 Chrome 中执行 Javascript 代码 "on the spot"?

javascript - select2 不调用 Ajax

c# - 将多个参数传递给 Threading.Timer 回调方法的最佳方法是什么?

python - 将抽象类用于事件处理程序回调是惯用的 Python 吗?

javascript - 想要使用 jquery 输入掩码插件验证用户单击 ip 地址字段的按钮

javascript - iPad 上 iframe 中的文本区域行为

C++函数回调