2012-07-30 70 views
0

所以我一直在努力編寫一個腳本,它接受來自10個不同字段的輸入,並且如果下拉列表中的任何內容被更改,popScore和popLevel會相應更新。我遇到了一個小問題,產生一個有10位小數的數字,所以我不得不將它舍入到2中。這個javascript適用於除Internet Explorer之外的所有瀏覽器。 是什麼導致它在Internet Explorer上失敗?Javascript併入jQuery不工作在Internet Explorer

下面我將javascript僅包含一個下拉以節省空間,但它們之間的差異是popScore和下拉菜單中項目的數量。 popLevel最高只能達到5.

任何幫助理解爲什麼它不起作用,非常感謝。謝謝。

<script type="text/javascript"> 
$(document).ready(function(){ 
    //global variables 
    var popLevel = 0; 
    var popScore = 0.00; 
    var q1=0; 
    var q2=0; 
    var q3=0; 
    var q4=0; 
    var q5=0; 
    var q6=0; 
    var q7=0; 
    var q8=0; 
    var q9=0; 
    var q10=0; 
$('.selectionbox1').change(function() { 
    if(q1 != 0){ 
     if(q1 == 1){ 
     popScore = popScore - 0.13; 
     } 
     else if(q1 == 2){ 
     popScore = popScore - 0.25; 
     } 
     else if(q1 == 3){ 
     popScore = popScore - 0.38; 
     } 
     else if(q1 == 4){ 
     popScore = popScore - 0.50; 
     } 
     else if(q1 == 5){ 
     popScore = popScore - 0.63; 
     } 
    } 
    var b = document.getElementById("q1").value; 
    if(b == 1){ 
     popScore = popScore + 0.13; 
    } 
    else if(b == 2){ 
     popScore = popScore + 0.25; 
     } 
    else if(b == 3){ 
     popScore = popScore + 0.38; 
    } 
    else if(b == 4){ 
     popScore = popScore + 0.50; 
     } 
    else if(b == 5){ 
     popScore = popScore + 0.63; 
    } 

    if(popScore > 4.00){ 
    popLevel=5; 
    } 
    else if(popScore > 3.00){ 
    popLevel=4; 
    } 
    else if(popScore > 2.00){ 
    popLevel=3; 
    } 
    else if(popScore > 1.00){ 
    popLevel=2; 
    } 
    else if(popScore > 0.00){ 
    popLevel=1; 
    } 

    //record the current value of the field changed 
    var e = document.getElementById("q1"); 
    q1=e.options[e.selectedIndex].value; 

    //round to 2 decimal places for score 
    popScore = parseFloat(popScore.toFixed(2)); 

    //update the fields for pop score and pop level 
    var txt = document.getElementById("popLevel"); 
    txt.innerHTML=popLevel; 
    var txt2 = document.getElementById("popScore"); 
    txt2.innerHTML=popScore; 
}); 
+3

哪個版本的IE和你得到的錯誤是什麼? – JavaKungFu 2012-07-30 17:25:45

+0

一些建議,以改善您的代碼。使用數組'q'而不是單個變量。另外,設置一個數組或者一個地圖(比如'value'),其中'1'映射到'0.13','2'映射到'0.25'等等。然後,你需要做的是'popScore = popScore - value [q [1]];' – 2012-07-30 17:28:21

回答

0

浮動數字不準確。爲了顯示目的,您應該始終圍繞它們。當我在我的JS控制檯上輸入2.48+1.49時,我得到了3.9699999999999998。任何使用http://en.wikipedia.org/wiki/IEEE_754的語言都是如此,這是使用最廣泛的浮點格式。

下面是對該問題的一個很好的解釋:http://docs.python.org/tutorial/floatingpoint.html它適用於Python,但正如我之前提到的,大多數語言使用相同的格式。

+0

我不認爲這是問題。他使用'toFixed(2)'。 – 2012-07-30 17:29:35

+0

@VivinPaliath OP由於浮點數的近似值而使用'toFixed(2)',但是OP寧願不必四捨五入。我的答案解釋說你必須圍繞它。 – 2012-07-30 17:30:40

+0

我嘗試過,但唯一的辦法就是使用'toFixed(2)' – fudge22it 2012-07-30 17:34:44

相關問題