開発環境
- OS X El Capitan - Apple (OS)
- Emacs (Text Editor)
- JavaScript (プログラミング言語)
- jQuery (Library)
- Safari(Web browser)
Exercises for Programmers: 57 Challenges to Develop Your Coding Skills (Brian P. Hogan 著、Pragmatic Bookshelf)のChapter 3(Calculations)、7(Area of a Rectangular Room)を取り組んでみる。
7(Area of a Rectangular Room)
コード(Emacs)
<input type="radio" id="radio_feet" name="unit0" value="feet" checked>
<label for="radio_feet">feet</label>
<input type="radio" id="radio_meter" name="unit0" value="meter">
<label for="radio_meter">meter</label>
<br>
<label for="length0">
What is the length of the room?
<input id="length0" type="number" value="15">
</label>
<br>
<label for="width0">
What is the width of the room?
<input id="width0" type="number" value="20">
</label>
<br>
You entered dimensions of <span class="length0"></span> by <span class="width0"></span>.
<br>
The area is<br>
<span id="area_feet0"></span> square feet<br>
<span id="area_meters0"></span> sqaure meters<br>
<script src="sample7.js"></script>
var CONVERSION_FACTOR = 0.09290304,
units = document.querySelectorAll('[name="unit0"]'),
input_length = document.querySelector('#length0'),
input_width = document.querySelector('#width0'),
inputs = [input_length, input_width],
lengths = document.querySelectorAll('.length0'),
widths = document.querySelectorAll('.width0'),
span_area_feet = document.querySelector('#area_feet0'),
span_area_meters = document.querySelector('#area_meters0'),
square,
squareFeetToMeters,
squareMetersToFeet,
display,
i,
max;
squareFeetToMeters = function (square_feet) {
return square_feet * CONVERSION_FACTOR;
};
squareMetersToFeet = function (square_meters) {
return square_meters / CONVERSION_FACTOR;
};
square = function (length, width) {
return length * width;
};
display = function () {
var length = parseFloat(input_length.value),
width = parseFloat(input_width.value),
unit,
square_feet,
square_meters,
i,
max;
for (i = 0, max = units.length; i < max; i += 1) {
if (units[i].checked) {
unit = units[i].value;
break;
}
}
if (unit === 'feet') {
square_feet = square(length, width);
square_meters = squareFeetToMeters(square_feet);
} else {
square_meters = square(length, width);
square_feet = squareMetersToFeet(square_meters);
}
for (i = 0, max = lengths.length; i < max; i += 1) {
lengths[i].innerText = length;
}
for (i = 0, max = widths.length; i < max; i += 1) {
widths[i].innerText = width;
}
span_area_feet.innerText = square_feet;
span_area_meters.innerText = square_meters;
};
display();
inputs.forEach(function (input) {
input.onkeyup = display;
input.onchange = display;
});
for (i = 0, max = units.length; i < max; i += 1) {
units[i].onchange = display;
}
You entered dimensions of by .
The area is
square feet
sqaure meters
0 コメント:
コメントを投稿