2014-03-29 90 views
0

我有問題。或者更像是一項任務或任何你可以稱之爲的任務。 看到我想要做的事情,但我需要訪問一個函數內的變量,我知道這已被問過,但我只是無法弄清楚。 其實我有兩個問題。函數內部的函數接受變量,Javascript

我正在嘗試製作一個表單,其中一個用戶出現兩個隨機數,然後他必須回答這兩個數字的總和。 這是我的代碼:

HTML

<button class="Btn" id="check" onclick="check()">Check!</button> 
<button class="Btn" onclick="newCalculation()">New Calculation</button> 
<label id="question"></label> 
<input id="answerBox" class="txtBox" type="text"></input> 

這兩個按鈕,一個標籤和一個文本框。第一個按鈕進行新的計算,第二個按鈕檢查文本框的值是否等於計算結果。該標籤用於計算顯示。

這是JavaScript的新的計算按鈕:

function newCalculation() { 
var firstnumber, secondnumber, answer; 
firstnumber = (Math.floor(Math.random()*10)+1)*10+(Math.floor(Math.random()*10)); 
secondnumber = (Math.floor(Math.random()*10)+1)*10+(Math.floor(Math.random()*10)); 
answer = firstnumber + secondnumber; 
document.getElementById("question").innerHTML = firstnumber + " + " + secondnumber + " = "; 
} 

至於我可以看到,這是所有分辯。但是當我必須檢查它是否正確時,我無法訪問這些變量。

Checkbutton

function check() { 
    if (document.getElementById("answerBox").innerHTML === newCalculation.answer) { 
    alert("Correct!") 
} 
    else { 
    alert("Wrong!") 
};} 

在控制檯登錄,它說用文本框右邊的值,但「不確定」的答案變量。如果我刪除「newCalculation」。它只是說變量是未定義的。 我只是想知道如何解決這個問題,並擁有所有這些工作。如果你能給出一個完整的代碼示例,那就太棒了!

感謝

回答

0

首先,input是自結束標記,它沒有打開/關閉標籤,像

應該

<input id="answerBox" class="txtBox" type="text"> 

,而不是

<input id="answerBox" class="txtBox" type="text"></input> 

Yo你應該從輸入標籤中得到這樣的值。

var compareVal = document.getElementById("answerBox").value; 

更新

當你要共享的變量,這是很好的做法,創造一流的,它是相對的屬性和方法,您可以訪問它就是你想要的paritcular方法屬性,像你案件。

的javaScript

var calc = function(){ 
    this.answer =""; //can access on newCalculation() and check() 

    this.newCalculation = function() { 
     var firstnumber, secondnumber, 
     firstnumber = (Math.floor(Math.random()*10)+1)*10+(Math.floor(Math.random()*10)); 
     secondnumber = (Math.floor(Math.random()*10)+1)*10+(Math.floor(Math.random()*10)); 
     this.answer = firstnumber + secondnumber; 
     document.getElementById("question").innerHTML = firstnumber + " + " + secondnumber + " = "; 
    }, 

    this.check = function() { 
     var checkedVal = parseInt(document.getElementById("answerBox").value, 10); 
     if (checkedVal === this.answer) { 
      alert("Correct!"); 
     }else { 
      alert("Wrong!"); 
     } 
    } 
} 

var myCal = new calc(); //creating object by calling class/constructor 

function checkAll(action){ 
    if(action == 'check'){ 
     myCal.check(); 
    } 

    if(action == 'newCalc'){ 
     myCal.newCalculation(); 
    } 
} 

HTML

<button class="Btn" id="check" onclick="checkAll('check')">Check!</button> 
<button class="Btn" onclick="checkAll('newCalc')">New Calculation</button> 
<label id="question"></label> 
<input id="answerBox" class="txtBox" type="text" value="20"/> 

DEMO

+0

那麼這正是我所需要的,謝謝! ;) –

0

當你在JavaScript中沒有其他塊聲明函數,它屬於在全球範圍內,因此變量newCalculation存在與類型function

我會建議是使它簡單,在全球範圍內宣佈

 var answer; 

- 在任何功能意義不是。然後當你在check()比較answer而不是newCalculation.answer

+0

我到目前爲止,但我希望它每次都做一個新的數字我稱之爲funktion? –