首页 > 解决方案 > 当输入到不同的文本框中时,程序会以不同的方式处理相同的字符串

问题描述

我有一个应该将链接组合在一起的程序。就像我的世界保存工具栏一样,你可以保存一组链接,然后输入一个组的名称,它会打开所有的。

但是,当将名称输入到用于获取链接的文本框中时,我的程序无法从 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>

标签: javascripthtmldomlocal-storage

解决方案


您正在读取页面加载getByName时输入元素的值。相反,您应该在需要时读取该值。所以定义为 DOM 元素(而不是它的值):getByName

var getByName = document.getElementById('getByName');

在您当前引用的地方,为属性访问器getByName添加后缀。.value例如:

var len = localStorage.getItem(getByName.value + '_length');

旁注:我发现为所有数据使用内存数据结构更容易,并且当向其中添加某些内容时,将完整的数据结构写入一个本地存储键,JSON 格式。你可能想调查一下。


推荐阅读