JSで単語帳を作ろう(前編)

JavaScript

JSを使って単語帳を作ってみよう。

準備

任意の場所にwordlistフォルダを作成し、その中にjsフォルダと、cssフォルダを作成する。

作成

1.wordlistフォルダの直下にindex.htmlを作成し以下のように記述する。

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>単語帳</title>
		<link rel="stylesheet" href="css/main.css">
		<script src="js/main.js"></script>
	</head>
	<body>
		<h1>単語帳</h1>
		<input type="text" id="en" placeholder="単語">
		<input type="text" id="ja" placeholder="意味">
		<button id="btn">登録</button>
		<p id="total">全0件</p>
		<table id="table"></table>
	</body>
</html>

実行してみよう。以下のように表示されれば成功だ。

main.js作成

入力した内容で表を作成していこう。jsフォルダ内にmain.jsを以下のように作成する。

'use strict';
window.onload=function(){
	const en=document.getElementById('en');	
	const ja=document.getElementById('ja');	
	const btn=document.getElementById('btn');	
	const total=document.getElementById('total');	
	const table=document.getElementById('table');	
	class Color{
		constructor(en,ja){
			this.en=en;
			this.ja=ja
		}
		showInfo(){
			return `<td>${this.en}</td><td>${this.ja}</td>`;
		}
	}
	let colors=[];
	btn.addEventListener('click',()=>{
		let color=new Color(en.value,ja.value);
		colors.push(color);
		en.value='';
		ja.value='';
		createTable();
	});
	function createTable(){
		table.innerHTML='<tr><th>単語</th><th>意味</th></tr>';
		for(let i=0;i<colors.length;i++){
			let tr=document.createElement('tr');
			tr.innerHTML=colors[i].showInfo();
			table.appendChild(tr);
			total.textContent=`全${colors.length}件`;
		}
	}
	createTable();
};

実行して、いくつか単語を登録してみよう。以下のように入力した内容が下に表示されれば成功だ。

main.css

テーブルにスタイルを当てよう。cssフォルダの中にmain.cssを作成し以下のように記述する。

#table{
	border-collapse:collapse;
}
td,th{
	border:1px solid #333;
	padding:0 10px;
	text-align:center;
}

[解説]
テーブルにボーダーに引くときにborder-collapseの指定をcollapseにしないと線が2重になってしまう。とても覚えにくいプロパティの一つだが、よく使うので知っておこう。

実行してみよう。テーブルに線が引かれた。
(現状はリロードするとデータが全部消えてしまうので再入力の必要がある)

前編終了

前編はここまでだ。ボタンを押すことで動的に要素を作成できるようになったがリロードすると全て消えてしまう。後編ではこれをブラウザに保存する仕組みを実装していく。

コメント

タイトルとURLをコピーしました