2017-04-07 4 views
0

Link to Codepenこの電卓の機能を実現する方法がわからない

非常に早い時期に数学プロジェクトが開始されます。

私はDRYコンセプトを適用しようとしましたが、私はどのようにわかりません。私はすべての数字に適用される関数を書くようになりましたが、途中でそれがうまくいかないことが分かりました。匿名関数を変更する必要がありますが、私はそれを実装する別の方法がわからないので、今はできません。

document.querySelector(".button").addEventListener("click", function) { 
    num = document.getElementById('something'); 

    if (num != null && num === document.getElementById("zero")) { 
    calculation = calculation.concat("0"); 
    } else if (num != null && num === document.getElementById("one")) { 
    calculation = calculation.concat("1"); 
    } else if (num != null === && num document.getElementbyId("two")) { 
    calculation = calculation.concat("2"); 
    } else if (num != nul && num === document.getElementbyId("three")) { 
    calculation = calculation.concat("3"); 
    } else if (num != nul && num === document.getElementbyId("four")) { 
    calculation = calculation.concat("4"); 
    } else if (num != nul && num === document.getElementbyId("five")) { 
    calculation = calculation.concat("5"); 
    } else if (num != nul && num === document.getElementbyId()) { 
    calculation = calculation.concat("6"); 
    } 
} 

各番号は表の中のボタンの中にあります。彼らはまた、どちらの番号であるかを識別するIDを持っています。私はコードを探していない、何かを盗もうとしたくない。ちょうど私が別々にできることについての提案を探しています。

+0

'NUM ===のdocument.getElementById(「ゼロ」)'別のオブジェクトに1つのオブジェクトを比較しているを参照してください。それらは異なるオブジェクトなので、これは常に「偽」です。その値を比較する必要があります。そしてある時点で、 'ヌル'の代わりに 'ヌル'と書いていました。 2番目の 'else if'は構文が正しくありません。 – Xufox

+0

一般的なポイント: 'document.querySelector("。button ")'ボタンのクラス*を持つ* first *要素を選択します。 '

答えて

0

あなたの最も簡単な方法は、共通の機能を書くことになります

var buttons = document.querySelectorAll("button"); 
 
for (var i = 0; i < buttons.length; i++) { 
 
    buttons[i].addEventListener(
 
    "click", 
 
    function() { 
 
    var current_value = this.innerHTML; //typed single number 
 
    var display_value = document.getElementById('display').value; //the value on the calculator display 
 
    var new_value = display_value + '' + current_value; //+''+ to make it string 
 
    document.getElementById('display').value = new_value; 
 
    }); 
 
}

は、これを試してみて、「+」フィルタリングすることにより、上記と同様の方法で例外と計算機能を追加「 - 」、等の値。

+1

このイベントハンドラは* first *ボタンにのみバインドされています。 – nnnnnn

+0

@nnnnnn:ありがとう。答えを編集しました。 –

+1

しかし、あなたの編集は、私が言ったこととは何の関係もありません。また、 'current_value'と' display_value'はすでに文字列であることに注意してください。 – nnnnnn

0

jqueryを使用すれば簡単だと思います。ちょっとした提案です。

フィディドをご覧ください。

私はすべての事業者のための「Calcは」次のjQuery

var calculation=''; 
$('button.show').click(function(){ 
calculation = calculation.concat($(this).text()); 
$('#screen').text(calculation); 
}); 
を使用して表示JavaScriptをbuttons..replaced我々はクリックしてクラスに画面上に表示したいすべてのボタンにクラスのショー」を追加しました計算のため

し、また追加のスクリプト

フィドルUpdated Fiddle

関連する問題