2016年8月11日木曜日

開発環境

Exercises for Programmers: 57 Challenges to Develop Your Coding Skills (Brian P. Hogan 著、Pragmatic Bookshelf)のChapter 2(Input, Processing, and Output)、5(Simple Math)を取り組んでみる。

5(Simple Math)

コード(Emacs)

<label for="first_number0">
  What is the first number?
  <input id="first_number0" type="number" min="0" step="1" value="10">
</label>
<br>
<label for="second_number0">
  What is the second number?
  <input id="second_number0" type="number" min="0" step="1" value="5">
</label>

<p>
  <span class="first_number0"></span> + <span class="second_number0"></span>
  = <span id="add0"></span>
</p>
<p>
  <span class="first_number0"></span> - <span class="second_number0"></span>
  = <span id="sub0"></span>
</p>
<p>
  <span class="first_number0"></span> * <span class="second_number0"></span>
  = <span id="mul0"></span>
</p>
<p>
  <span class="first_number0"></span> / <span class="second_number0"></span>
  = <span id="div0"></span>
</p>

<script src="sample5.js"></script>
var input_first_number = document.querySelector('#first_number0'),
    input_second_number = document.querySelector('#second_number0'),
    inputs = [input_first_number, input_second_number],
    span_first_number = document.querySelectorAll('.first_number0'),
    span_second_number = document.querySelectorAll('.second_number0'),
    add = document.querySelector('#add0'),
    sub = document.querySelector('#sub0'),
    mul = document.querySelector('#mul0'),
    div = document.querySelector('#div0'),
    calc;

calc = function () {
    var first_number = parseInt(input_first_number.value, 10),
        second_number = parseInt(input_second_number.value, 10),
        i,
        max;

    for (i = 0, max = span_first_number.length; i < max; i += 1) {
        span_first_number[i].innerText = first_number;
        span_second_number[i].innerText = second_number;
    }

    add.innerText = first_number + second_number;
    sub.innerText = first_number - second_number;
    mul.innerText = first_number * second_number;
    div.innerText = first_number / second_number;
};

calc();

inputs.forEach(function (input) {
    input.onkeyup = calc;
});

+ =

- =

* =

/ =

0 コメント:

コメントを投稿