gpt4 book ai didi

javascript - 为什么这个 function = true 在 Google Chrome 而不是 Firefox 中工作?

转载 作者:行者123 更新时间:2023-11-30 13:23:58 26 4
gpt4 key购买 nike

在 Firefox 中,这部分代码似乎永远不会返回 true。然而它在谷歌浏览器中运行良好

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, digitsOnly) 中的事件引用。但如果是这样的话,具体是什么?

/* 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 的表达式也是作为断言为真。

关于javascript - 为什么这个 function = true 在 Google Chrome 而不是 Firefox 中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9219993/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com