2016年10月7日金曜日

開発環境

Exercises for Programmers: 57 Challenges to Develop Your Coding Skills (Brian P. Hogan 著、Pragmatic Bookshelf)のChapter 10(Full Programs)、56(Tracking Inventory)を取り組んでみる。

56(Tracking Inventory)

コード(Emacs)

HTML5

<div id="output0"></div>
<label for="name0">Name: </label>
<input id="name0" type="text"><br>
<label for="serial0">Serial Number: </label>
<input id="serial0" type="text"><br>
<label for="value0">Value: $</label>
<input id="value0" type="number" step="0.01"><br>

<button id="add0">追加</button>

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"></script>
<script src="sample56.js"></script>

JavaScript

{
    'use strict';
    let div_output = document.querySelector('#output0'),
        input_name = document.querySelector('#name0'),
        input_serial = document.querySelector('#serial0'),
        input_value = document.querySelector('#value0'),
        button_add = document.querySelector('#add0');

    const KEY = 'TrackingInventory';

    let getInventory = () => {
        let json = localStorage.getItem(KEY);
        
        return json === null ? [] : JSON.parse(json);    
    };
    let addItem = () => {
        let inventory = getInventory(),
            name = input_name.value,
            serial = input_serial.value,
            value = input_value.value,
            item = {name: name, serial: serial, value: value};

        inventory.push(item);
        localStorage.setItem(KEY, JSON.stringify(inventory));

        div_output.innerHTML =
            '<table border="1"><tr><th>' +
            ['Name', 'Serial Number', 'Value'].join('</th><th>') +
            '</th></tr>' +
            inventory.map(
                (item) => `<tr><td>${item.name}</td>` +
                    `<td>${item.serial}</td>` +
                    `<td>${item.value}</td></tr>`).join('') + 
            '</table>';
    };
    button_add.onclick = addItem;
}



0 コメント:

コメントを投稿

Comments on Google+: