1

我正在使用以下代码来防止某些字符被输入到文本框中。除了 iPad 和 iPhone 上的 Chrome 和 Safari(webkit 移动设备?)外,它运行良好。在 Safari 和 Chrome 中的 Mac 上运行良好。任何想法如何限制这些设备的数字和冒号?

jQuery.fn.forceNumeric = function (allowDecimal, allowColon)
{
    return this.each(function ()
    {
        $(this).keydown(function (e)
        {
            var key = e.which || e.keyCode;

            if (!e.shiftKey && !e.altKey && !e.ctrlKey &&
            // numbers   
                    key >= 48 && key <= 57 ||
            // Numeric keypad
                    key >= 96 && key <= 105 ||
            // period, comma, minus adn period on keypad
            //      key == 190 ||   // period
            //      key == 188 ||   // comma
            //      key == 109 ||   // minus
            //      key == 110 ||   // period on keypad
            // Backspace and Tab and Enter
                    key == 8 || key == 9 || key == 13 ||
            // Home and End
                    key == 35 || key == 36 ||
            // left and right arrows
                    key == 37 || key == 39 ||
            // Del and Ins
                    key == 46 || key == 45)
                return true;
            else if (!e.shiftKey && !e.altKey && !e.ctrlKey && allowDecimal && key == 190) // period
                return true;
            else if (!e.shiftKey && !e.altKey && !e.ctrlKey && allowDecimal && key == 110) // period on keypad
                return true;
            else if (e.shiftKey && (key == 186 || key == 59) && allowColon) // colon (ie & chrome = 186, ff = 59)
                return true;
            else
                return false;
        });
    });
4

2 回答 2

1

我们使用类似的逻辑(keyCode 48-75 和 96-105)并且它有效。我没有测试您的示例代码,但是您的第一个大量使用且没有括号if的语句让我有点担心。也许尝试放入一些括号组并再试一次?&&||

于 2012-12-19T20:46:04.750 回答
0

这就是我最终做的事情 - 检测 iOS 设备并将 else 添加到原始脚本中。可能有更好的方法...

function isiPhone(){
    return (
        //Detect iPhone
        (navigator.platform.indexOf("iPhone") != -1) ||
        //Detect iPod
        (navigator.platform.indexOf("iPod") != -1)
    );
}

var isiPad = navigator.userAgent.match(/iPad/i) != null;

...
else if ((isiPhone() || isiPad) && (key == 186 || key == 59) && allowColon) // colon   (iOS devices don't have a shift key)
                return true;
于 2012-12-20T00:50:47.670 回答