【问题标题】:Stopping a function inside a namespace停止命名空间内的函数
【发布时间】:2015-03-05 02:05:22
【问题描述】:

我有一个命名空间,它有一种方法可以阻止在按键事件中输入某些字符以进行输入。如果检测到该字符,它会返回 false 但我认为因为它是在触发按键时调用的,所以仍然会输入该字符。我该如何解决这个问题?

如果我将函数从命名空间中取出,它会按预期工作,但我不希望这样。

HTML

<div id="personal-info">
    <input id="first-name" class="personal-info" autofocus/><p id="error-first-name" class="error-text"></p>
    <input id="last-name" class="personal-info"/><p id="error-last-name" class="error-text"></p>
</div>

Javascript:

    fsa = (function() {

        //OK - get selected element ID and write ID
        var inputId = "";
        var sigId = "";
        var errId = "";
        function GetAndSetLoc() {
            inputId = document.activeElement.id;
            sigId = "sig-" + document.activeElement.id;
            errId = "error-" + document.activeElement.id;
        }
        var thisId = "";

        // on button down, if the character is illegal, change the css of the error box
        function showError(keyCode) {
        var keys = [13,
        "<".charCodeAt(0),
        ">".charCodeAt(0),
        "$".charCodeAt(0),
        "(".charCodeAt(0),
        ")".charCodeAt(0),
        "?".charCodeAt(0),
        "{".charCodeAt(0),
        "}".charCodeAt(0),
        "/".charCodeAt(0),
        "#".charCodeAt(0),
        "&".charCodeAt(0),
        "*".charCodeAt(0),
        "@".charCodeAt(0),
        "~".charCodeAt(0)
        ];

            var index;
            for (index = 0; index < keys.length; ++index) {

                if (keys[index] === keyCode) {
                    errorObject = $('#' + errId);
                    errorObject.html("Sorry, invalid character.").addClass('error');
                    setTimeout(function() {
                        errorObject.html("Sorry, invalid character.").removeClass('error');
                    }, 2000);
                    return false;
                }
            }
        }

        return {
            GetAndSetLoc: GetAndSetLoc,
            showError: showError
        }

    })();

    // --------- Call the functions

    //OK - get current read and write ids
    $('.personal-info').focus(function(){
        fsa.GetAndSetLoc();
    });

    $("input").keypress(function(e) {
        fsa.showError(e.keyCode);
    });

【问题讨论】:

  • 尝试使用 keydown 事件

标签: javascript jquery namespaces


【解决方案1】:

在发生错误时从按键事件中返回 false

$("input").keypress(function(e) {
       return fsa.showError(e.keyCode);
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-13
    • 1970-01-01
    • 2018-04-24
    • 1970-01-01
    • 2018-08-14
    • 2016-07-10
    • 2016-06-19
    • 2012-06-11
    相关资源
    最近更新 更多