如何在Jquery Mobile歌词应用中无数据库存储并展示新增歌词
解决方案:用
localStorage实现前端数据持久化 首先得明确:纯前端JavaScript无法直接写入本地.txt文件(除非通过File API让用户手动下载文件,但刷新页面后数据会丢失),所以最适合你需求的方案是使用浏览器的localStorage——这是一种内置的前端存储机制,可以持久化保存字符串数据,页面刷新甚至关闭浏览器后数据依然存在。
下面是具体的实现步骤和修改后的代码:
核心思路
- 监听表单提交事件,获取用户输入的歌曲信息
- 将歌曲数据以JSON数组的形式存入
localStorage - 页面加载时读取
localStorage中的数据,动态渲染到ListView - 动态添加列表项后,调用jQuery Mobile的
listview('refresh')方法更新样式
修改后的完整代码
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Mobile App using Jquery</title> <link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" /> <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script> <script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.12/css/all.css" integrity="sha384-G0fIWCsCzJIMAVNQPfjH08cyYaUtMwjJwqiRKxxE/rx96Uroj1BtIQ6MLJuheaO9" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <style> .fullscreen{ max-width: 100%; height: auto; } h1{ font-size: 14pt; color: #E76C67; margin-top: 0%; } h2{ font-size: 12pt; color: #444444; margin-top: -3%; } </style> </head> <body> <!--Index Page starts Here --> <div data-role="page" id="demo-page" data-url="demo-page"> <div data-role="header"> <h1>Gospel Songs </h1> <a href="#" id="home" data-icon="home" data-iconpos="notext"> Home</a> <a href="#" class="jqm-search-link ui-shadow ui-btn ui-btn-icon-notext ui-corner-all ui-icon-search ui-nodisc-icon ui-alt-icon ui-btn-right">Search</a> </div><!-- /header --> <div role="main" class="ui-content"> <ul data-role="listview" data-autodividers="true" id="sortedList" data-filter="true"> <!-- 初始歌曲项 --> <li> <a href="#"> <h1>All The Way My Saviour Leads Me lyrics</h1> <p>All the way my Savior leads me What have I to ask beside?.... </p> </a> </li> <li> <a href="#"> <h1>Amazing Grace lyrics</h1> <p>"Amazing Grace, how sweet the sound,...</p> </a> </li> </ul><!-- /listview --> </div><!-- /content --> <footer data-role="footer" data-position="fixed"> <nav data-role="navbar"> <ul> <li><a href="#demo-page" data-icon="home"> Home </a></li> <li><a href="#demo-page" data-icon="grid">Photos</a></li> <li><a href="#add_song" data-icon="plus" data-transition="flip"> Add Song </a></li> </ul> </nav> </footer><!-- /footer --> </div> <div data-role="page" id="add_song"> <div data-role="header"> <h1>Add Songs Lyrics</h1> <a href="#demo-page" data-icon="back" data-iconpos="notext"> Back</a> </div> <div role="main" class="ui-contain"> <form id="myform"> <label for="song_name">Song Name:</label> <input type="text" name="song_name" id="song_name" value="" required> <label for="lyricist_name">Lyricist Name:</label> <input type="text" name="lyricist_name" id="lyricist_name" value="" required> <label for="song_lyrics">Song Lyrics:</label> <textarea name="song_lyrics" id="song_lyrics" required></textarea> <input type="submit" value="Submit"> </form> </div> <footer data-role="footer" data-position="fixed"> <nav data-role="navbar"> <ul> <li><a href="#demo-page" data-icon="home"> Home </a></li> <li><a href="#demo-page" data-icon="grid">Photos</a></li> <li><a href="#add_song" data-icon="plus"> Add Song </a></li> </ul> </nav> </footer><!-- /footer --> </div><!-- ADD_SONG_PAGE content --> <script> // 页面初始化时加载本地存储的歌曲 $(document).on("pagecreate", "#demo-page", function() { loadSavedSongs(); }); // 处理表单提交 $(document).on("submit", "#myform", function(e) { e.preventDefault(); // 阻止默认表单提交行为 // 获取表单输入值 const songName = $("#song_name").val().trim(); const lyricistName = $("#lyricist_name").val().trim(); const songLyrics = $("#song_lyrics").val().trim(); // 验证输入 if (!songName || !lyricistName || !songLyrics) { alert("Please fill all fields!"); return; } // 构造歌曲对象 const newSong = { name: songName, lyricist: lyricistName, lyrics: songLyrics }; // 从localStorage获取现有歌曲列表,不存在则初始化空数组 let songs = JSON.parse(localStorage.getItem("gospelSongs")) || []; // 添加新歌曲 songs.push(newSong); // 存回localStorage localStorage.setItem("gospelSongs", JSON.stringify(songs)); // 清空表单 $("#myform")[0].reset(); // 跳转回首页并刷新列表 $.mobile.changePage("#demo-page", { transition: "flip" }); loadSavedSongs(); }); // 加载并渲染保存的歌曲 function loadSavedSongs() { const songs = JSON.parse(localStorage.getItem("gospelSongs")) || []; const $list = $("#sortedList"); // 先移除之前动态添加的歌曲项(避免重复渲染) $list.find(".dynamic-song").remove(); // 遍历歌曲列表,添加到ListView songs.forEach(song => { const listItem = ` <li class="dynamic-song"> <a href="#"> <h1>${song.name} lyrics</h1> <p>By ${song.lyricist}<br>${song.lyrics.substring(0, 50)}...</p> </a> </li> `; $list.append(listItem); }); // 刷新ListView样式,确保jQuery Mobile样式生效 $list.listview("refresh"); } </script> </body> </html>
关键修改说明
- 移除无效链接:原代码中列表项里的空
<a href="#A1">标签,现在统一成一个链接容器,避免布局混乱 - 修正导航跳转:把
href="index.html"改成href="#demo-page",符合jQuery Mobile单页应用的跳转规则 - 添加表单验证:确保用户填写所有必填字段,避免空数据存入
- localStorage操作:
- 用
JSON.parse()和JSON.stringify()处理数组数据(因为localStorage只能存储字符串) - 每次提交时更新存储的歌曲数组,保证数据持久化
- 用
- 动态渲染逻辑:
- 页面初始化时自动加载保存的歌曲
- 提交表单后刷新列表并调用
listview("refresh"),确保jQuery Mobile的样式正确应用到新添加的项
其他可选方案
- sessionStorage:和localStorage类似,但数据只在当前会话有效,关闭浏览器后会自动清除
- IndexedDB:适合存储大量数据的场景,支持更复杂的查询,但API相对复杂,你的应用用localStorage完全足够
内容的提问来源于stack exchange,提问作者user9306264
相关产品推荐
相关产品推荐

