簡體   English   中英

Javascript密碼不能在Firefox中運行,但在chrome中運行良好

[英]Javascript keycodes not working in firefox but works well in chrome

我只是在進行表單驗證,其中哪個電話號碼只能是數字! 代碼適用於chrome,但不適用於Firefox和IE。 請給我一些解決方案

我的代碼如下

function noLet(event) {
    if (event.keyCode == 46 || event.keyCode==8 || event.keyCode > 47 && event.keyCode <      58) {
        event.returnValue = true;
    } 
    else {
        event.returnValue = false;
    }
}

HTML:

 onkeypress="noLet(e)"><label id="mobph"></label><font 

size="1"><br>Max 10 numbers only allowed!</font> 

我可以建議以下代碼來解決您的問題。 這就是我在做的事情。 測試和工作就像一個魅力,即chrome和firefox:

//return numbers and backspace(charCode == 8) only
function noLet(evt) {
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode >= 48 && charCode <= 57 || charCode == 8)
        return true;
    return false;

您可以使用鍵/字符代碼來檢測按下的鍵是否為數字。 首先,您必須檢測密鑰/字符代碼是否跨瀏覽器(請記住使用event.keypress作為事件以進一步確保兼容性) 然后,將其從十進制值轉換為其字符。 然后你可以使用parseInt()將它解析為整數,如果函數內的第一個值不能被解析為int,它將返回NaN 如果它是NaN ,則阻止默認操作。

var numbersOnly = function(e){
    var charCode = (typeof e.which === "number") ? e.which : e.keyCode,
        chr = String.fromCharCode(charCode);
    if(isNaN(parseInt(chr, 10))) e.preventDefault();
}

<input type="text" name="phoneNumber" onkeypress="numbersOnly(event);">

因為在Firefox上,至少它是charCode ,而不是keyCode處理程序中的keyCode ,並且忽略“returnValue”(調用preventDefault()來停止插入)。

有瀏覽器的兼容性問題。 這是我在一些RND發現的解決方案。 希望所以它會以某種方式幫助你; 點擊這里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM