我正在使用以下代码来防止将某些字符输入到文本框中。除了 iPad 和 iPhone 上的 Chrome 和 Safari(webkit mobile?),它工作正常。在 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;
});
});
最佳答案
我们使用类似的逻辑(keyCode 48-75 和 96-105)并且它有效。我没有测试过你的示例代码,但是你的第一个 if
语句大量使用了 &&
和 ||
没有括号给我一个很少关心。也许尝试放入一些括号并再试一次?
关于jquery - 在 iOS 上的 Safari 和 Chrome 中只允许数字和冒号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13960679/