2012-02-09 32 views
1

在Firefox中,代碼的這部分似乎永遠不會返回true。然而,它的工作原理非常清楚谷歌瀏覽器爲什麼這個函數= true在谷歌瀏覽器中工作,但不是Firefox?

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

什麼應該發生的是,如果用戶在輸入框中輸入一個從1數到5的ID E1Rating該函數返回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; 
     } 

    } 
} 

回答

3

您必須將event定義爲函數參數。 Google Chrome和IE支持非標準的全球event屬性,該屬性指的是最新的事件對象。

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

注:if (.. == true)可以安全地與if (...)替換,因爲它等於真任何表達式,也可作爲一個斷言真。

+0

謝謝!我將在哪裏瞭解這些瀏覽器差異?我嘗試搜索Chrome和Firefox JavaScript事件差異,但無法找到您告訴我的內容。 – OneBigNewbie 2012-02-09 23:08:00

+0

對於Firefox和大多數其他瀏覽器,我在搜索關鍵字前加上「mdn」,例如「mdn event」 - > [Mozilla Developer Network> DOM> Event](https://developer.mozilla.org/en/DOM/事件)。對於IE瀏覽器,我搜索了「msdn javascript event」,並得到了[這個頁面](http://msdn.microsoft.com/en-us/library/ms535863%28v=vs.85%29.aspx)。 – 2012-02-10 15:00:39

相關問題