javascript - 当输入到不同的文本框中时,程序会以不同的方式处理相同的字符串
问题描述
我有一个应该将链接组合在一起的程序。就像我的世界保存工具栏一样,你可以保存一组链接,然后输入一个组的名称,它会打开所有的。
但是,当将名称输入到用于获取链接的文本框中时,我的程序无法从 localStorage 获取列表。但是当我只使用文本框的值来命名组时,它工作正常。
我的代码在这里:
var groupName = document.getElementById('name');
var link = document.getElementById('newLink');
var linkCounter = 0
var getByName = document.getElementById('getByName').value
function startGroup() {
localStorage.setItem(groupName.value, groupName.value);
console.log(localStorage.getItem(groupName.value))
}
function addLink() {
linkCounter++;
localStorage.setItem(groupName.value + '_link' + linkCounter, link.value);
console.log(localStorage.getItem(groupName.value + '_link' + linkCounter))
}
function saveGroup() {
localStorage.setItem(groupName.value + '_length', linkCounter);
console.log(localStorage.getItem(groupName.value + '_length'))
alert(groupName.value);
}
function getGroup() {
// if I replace getByName with groupName.value, it works fine.
var len = localStorage.getItem(getByName + '_length')
console.log(len)
for (var x = 1; x <= len; x++) {
window.open(localStorage.getItem(getByName + '_link' + x));
}
}
<!DOCTYPE html>
<html>
<a href='readit.html'>READ THIS BEFORE USING</a>
<p>WHEN ADDING A LINK YOU NEED TO PASTE IT OR ADD HTTPS:// TO THE BEGINNING OF THE LINK.</p>
<div id='toolbars'>
<p>Open a group!</p>
</div>
<div id='create'>
<p>Create some bookmark groups!</p>
<input type='text' placeholder='name your group' id='name'>
<button onclick='startGroup()'>Let's add some links!</button>
<br>
<input type='text' placeholder='add a link' id='newLink'>
<button onclick='addLink()'>Submit</button>
<br>
<button onclick='saveGroup()'>SAVE</button>
</div>
<div id='preview'>
<br><br>
<button onclick='getGroup()'>Open this group</button>
<input type="text" id="getByName">
</div>
</html>
<script src="script.js"></script>
解决方案
您正在读取页面加载getByName
时输入元素的值。相反,您应该在需要时读取该值。所以定义为 DOM 元素(而不是它的值):getByName
var getByName = document.getElementById('getByName');
在您当前引用的地方,为属性访问器getByName
添加后缀。.value
例如:
var len = localStorage.getItem(getByName.value + '_length');
旁注:我发现为所有数据使用内存数据结构更容易,并且当向其中添加某些内容时,将完整的数据结构写入一个本地存储键,JSON 格式。你可能想调查一下。
推荐阅读
- python - 如果从我的生产服务器向其他生产服务器发出 httprequest,则会出现连接错误,但它是使用 localhost 完成的
- html - 如何在同一页面上运行多个关键帧
- c# - 将 CSV 文件读取到嵌套对象
- laravel - 运行npm时如何删除CSS文件中的@charset?
- javascript - 用 id 替换列表元素,覆盖它并更新 DOM
- python - Dialogflow 统一响应跨多个平台
- jmeter - CSV 数据配置无法与我的 Thread-Loop 一起正常工作
- angular - canDeactivate 在第一次返回 false 的情况下,下一次 true 导航两次
- apache-spark - 如何识别以 kafka 为源的 Spark 结构化流中的消息来源?
- jquery - 首次加载页面时,Jquery UI 自动完成功能不起作用