2015-06-15 37 views
1

這裏很新穎,對於基本問題表示歉意。試圖完成奧丁項目的構建計算器的挑戰(http://www.theodinproject.com/javascript-and-jquery/on-screen-calculator如何顯示和存儲按鈕值?

並努力使數字出現後,他們被點擊。另外,如何將該值存儲在一個變量或數組中,然後用於以後的計算?

這裏是我JS的摘錄:

$(".numbers").on("click", function() { 

$+(this).text() 

    ;}); 

而我的HTML(注意我用的jsfiddle,因此缺乏HTML打開和關閉標籤等:

<script src="jquery-1.11.3.min.js"></script> 

<div class="numbers"> 
<button type="button">0</button> 

<button type="button">1</button> 

<button type="button">2</button> 

<button type="button">3</button> 

<button type="button">4</button> 

<button type="button">5</button> 

<button type="button">6</button> 

<button type="button">7</button> 

<button type="button">8</button> 

<button type="button">9</button> 

</div> 

<div class = "operators"> 
<button type="button">+</button> 
<button type="button">-</button> 
<button type="button">*</button> 
<button type="button">/</button> 
<button type="button">=</button> 
<button type="button">clear</button> 
</div> 
+0

如果你使用jsfiddle,並且你已經在那裏設置了一個隔離問題的演示,那麼鏈接到jsfiddle本身就非常好 –

回答

1

要將按鈕的值存儲在變量中,您可以這樣做。

$('button').on('click', function(){ 
    var i = $(this).text(); 
    console.log(i); // print the value of i in the console 
}); 

一旦你有你需要能夠整理點擊每個按鈕的值等,從而計算器的「顯示屏」上的值。

HTML

<div class="display"></div> 

的JavaScript

$('button').on('click', function(){ 
    var i = $(this).text(); 
    var display = $('.display'); 

    display.text(display.text() + i); 
}); 

希望這可以幫助你指出正確的方向。

+0

感謝Craig(以及所有其他答案)!超級有用,特別感謝快速響應。最後一個問題,因爲我的#按鈕(0-9)需要做與我的操作員按鈕(+, - 等)不同的事情,所以我希望將on.click()函數引用到整體包裝div,例如我的div class =數字。但是當我用$(「。numbers」)而不是按鈕使用你的方法時,它不起作用? – Noobprogrammer

+0

沒問題!爲了回答你的問題,使用'$('。numbers')。find('button')。on('click')'將一個點擊處理程序附加到'div.numbers'中的所有'buttons' –

0

我不是您是否使用TextArea?

對於存儲值,在您的功能內部做類似

var num = $ +(this).text()

除此之外,您需要更具體。

0

以下jsfiddle演示瞭如何做你想做的。

// array is defined outside the click handler 
var clickedArray = []; 

$('button').on('click',function() { 
    // get the button that was clicked 
    var buttonClicked = $(this).html(); 
    console.log(buttonClicked); 

    // store it as the last element in the array 
    clickedArray.push(buttonClicked); 
    console.log(clickedArray); 

    // and output it to the screen 
    $('.js-calc-out').append(buttonClicked); 
}); 

注意要點:

  1. 陣列被單擊事件處理程序之外定義,因此它可以沒有被每個點擊事件被觸發時重置使用。這個數組將一直存在,直到頁面被刷新或故意未被設置,並且您可以在需要時訪問它。
  2. html()功能檢索任何給定的HTML元素的內容,在這種情況下,它是單擊按鈕,它是使用$(this)(任何觸發事件的元素使用this檢索到的,然後使用該元素將其轉換爲jquery對象$()函數)。
  3. push()功能用於最新的點擊的元素附加到在點1
  4. .js-calc-out提到的陣列的端部是一個HTML元素,這是我們append()最新點擊,這意味着點擊的序列被輸出。
  5. console.log聲明會向檢查員輸出一些內容,這可以幫助您看到流程的發展。

PS。這是一個簡化的解決方案,考慮到您在學習曲線上的當前位置;理想情況下,您希望使用對象將數據和功能封裝在JavaScript中,並避開全局名稱空間。