###前提・実現したいこと
JavaScriptでローカルストレージ(localstrage)を利用したい
リンク先のコードをそのまま使用しています。画面に「こんにちはlocalStorage」と表示させるだけです。
http://team-lab.github.io/skillup-nodejs/1/6.html
###発生している問題・エラーメッセージ
画面になにも表示されない。 Chromeのコンソールを見てもエラーは表示されていないのでどうしたらいいか分からない
###該当のソースコード
HTML/JavaScript
1<!DOCTYPE html> 2<html lang="ja"> 3 <head> 4 <meta charset="UTF-8" /> 5 <title>JavaScriptのサンプル</title> 6 <script type="text/javascript"> 7 function (){ 8 // messageというキーに「こんにちはlocalStorage」という値を保存 9 localStorage.setItem("message", "こんにちはlocalStorage"); 10 // messageというキーに保存した値を取得して表示 11 var val = localStorage.getItem("message"); 12 document.querySelector("#result").innerHTML = val 13 } 14 </script> 15 </head> 16 <body> 17 <div id="result"></div> 18 </body> 19 20</html> 21 22
###試したこと
ローカルストレージを使用している以下のサンプルコードは動く。
どこで違いが出ているのか分かっていない。
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8" /> <title>JavaScriptのサンプル</title> 保存したい文字列:<br> <textarea id="edit_00" style="width:100%; height:100px; margin:0px 0px 5px 0px;"></textarea><br> <input type="button" id="button_00_load" style="width:80px; height:40px; margin:0px 0px 10px 0px;" value="読み込み"> <input type="button" id="button_00_save" style="width:80px; height:40px; margin:0px 0px 10px 0px;" value="保存"> <input type="button" id="button_00_del" style="width:80px; height:40px; margin:0px 0px 10px 0px;" value="削除"> <script type="text/javascript"> <!-- // 匿名関数内で実行 (function (){ // テキストフォームの element を取得 var element_edit = document.getElementById("edit_00"); var element; // 読み込みボタンの element を取得 element = document.getElementById("button_00_load"); // ボタンが押されたときに実行されるイベント element.onclick = function (){ try{ // "test_key" からデータを取り出す element_edit.value = localStorage.getItem("test_key"); }catch(e){ // エラーを出力 element_edit.value = e + "\n" + element_edit.value; } }; // 保存ボタンの element を取得 element = document.getElementById("button_00_save"); // ボタンが押されたときに実行されるイベント element.onclick = function (){ try{ // "test_key" にデータを保存する localStorage.setItem("test_key",element_edit.value); }catch(e){ // エラーを出力 element_edit.value = e + "\n" + element_edit.value; } }; // 削除ボタンの element を取得 element = document.getElementById("button_00_del"); // ボタンが押されたときに実行されるイベント element.onclick = function (){ try{ // "test_key" のデータを削除する localStorage.removeItem("test_key"); }catch(e){ // エラーを出力 element_edit.value = e + "\n" + element_edit.value; } }; })(); //--> </script> </head> <body> <div id="result"></div> </body> </html>
###補足情報(言語/FW/ツール等のバージョンなど)
特になし。
回答2件
あなたの回答
tips
プレビュー