为什么这个函数在谷歌浏览器中是真的,而在火狐浏览器中则不然

Why is this function = true working in Google Chrome but not Firefox?

本文关键字:火狐浏览器 函数 谷歌浏览器 为什么 真的      更新时间:2023-09-26

在Firefox中,这部分代码似乎从未返回true。然而,它在谷歌Chrome 中运行得非常好

if(restrictCharacters(this, event, digitsOnly)==true)

应该发生的是,如果用户在ID为E1Rating的输入框中输入一个从1到5的数字,则函数将返回true并运行嵌套在下面的代码。但在Firefox中,参与者输入号码后不会发生任何事情。

我把代码精简到Firefox中不起作用的部分。所以你可以看到它是如何被使用的。

document.getElementById("E1TimeStart").value = startTime;       
$('#E1Rating').keyup(function() {
    if(restrictCharacters(this, event, digitsOnly)==true){                  
        clearTimeout(mytimeout);                                                                        
        var rateTime = new Date().getTime();                
        $('#E1Rate').hide();                                                
        document.getElementById("E1TimeEnd").value = rateTime;              
        PrepareBox2();                                                      
    }
    else{
        //Do nothing and wait for the timeout
    }
});

};

这是restrictCharacters函数。我知道它能工作,因为它再次在Chrome中工作。此外,如果您在if==true函数之外使用该函数,则该函数在Firefox中也能工作。通过搜索和尝试,我怀疑它可能是(this,event,digitalsOnly)中的事件引用。但如果是这样的话,具体是什么?

/* Purpose: Code will restrict false until it detects the numbers 1 through 5 */
/* Code Source: originally from qodo.co.uk */
// create as many regular expressions here as you need:
var digitsOnly = /[1-5]/g;
function restrictCharacters(myfield, e, restrictionType) {
    if (!e) var e = window.event
    if (e.keyCode) code = e.keyCode;
    else if (e.which) code = e.which;
    var character = String.fromCharCode(code);
    // if they pressed esc... remove focus from field...
    if (code==27) { this.blur(); return false; }
    // ignore if they are press other keys
    // strange because code: 39 is the down key AND ' key...
    // and DEL also equals .
    if (!e.ctrlKey && code!=9 && code!=8 && code!=36 && code!=37 && code!=38 && (code!=39 || (code==39 && character=="'")) && code!=40) {
        if (character.match(restrictionType)) {
            return true;
        } else {
            return false;
        }
    }
}

您必须将event定义为函数参数。Google Chrome和IE支持非标准的全局event属性,该属性指的是最新的事件对象。

$('#E1Rating').keyup(function(event) { //<--
    if(restrictCharacters(this, event, digitsOnly)){

注意:if (.. == true)可以安全地替换为if (...),因为任何等于true的表达式作为断言也是true。