如何从LocalStorage中调用某些内容并使其动态

How do i call something out from my LocalStorage and make the thing dynamic

本文关键字:动态 LocalStorage 调用      更新时间:2023-09-26

我目前正试图刺激一个论坛。到目前为止,我所做的是当一个用户问一个问题时

  1. 主题和问题将保存到一个对象中,并推送到一个数组中
  2. 在主页面上,将显示阵列中的所有对象
  3. 我将能够点击每个显示的链接

但棘手的部分来了。如何使用同一个HTML并动态更改其中的代码。

我知道我调用的是使用数组[0]。问题是更改INNERHTML代码的内容。但我不知道如何制作一个特定的数组[数字]。

例如。如果我有一个长度为0-4的数组!当我点击第一个链接时,我想调用数组[0]。当我点击第二个链接时,后面跟着array[1]!我该怎么做!

我发现的另一个解决方案是使用URL哈希。然而,为了使用URL哈希,如果我想让我的所有数组对象都是动态的,我必须制作5个页面,对吗?

希望你们能理解我的意思!

根据我收集的信息,您有一系列问题,如

var questions = [{
  title: 'Question 1',
  description: 'something about Question 1'
}, {
  title: 'Question 2',
  description: 'something about Question 2'
}]

您希望能够显示每个问题的描述,而无需实际导航到新页面。这可以通过简单的javascript(使用jQuery更干净)实现。

以下是一种可以构建的普通js方法:

var questions = [{
  title: 'Question 1',
  description: 'something about Question 1'
}, {
  title: 'Question 2',
  description: 'something about Question 2'
}]
var questionContainer = document.getElementById('questions');
var descriptionContainer = document.getElementById('description');
var contentContainer = document.getElementById('content');
var backBtn = document.getElementById('back-btn');
questions.forEach(function(question) {
  var q = document.createElement('div');
  q.innerText = question.title;
  q.className = 'question';
  q.addEventListener('click', function() {
    contentContainer.innerText = question.description;
    descriptionContainer.style.display = 'block';
    questionContainer.style.display = 'none';
  })
  questionContainer.appendChild(q);
})
backBtn.addEventListener('click', function() {
  descriptionContainer.style.display = 'none';
  questionContainer.style.display = 'block';
})
.question:hover,
#back-btn:hover {
  color: blue;
  cursor: pointer;
}
<div id="questions"></div>
<div id="description" style="display: none;">
  <div id="back-btn">Back</div>
  <div id="content"></div>
</div>

请注意这适合四处玩耍或个人项目。然而,最终结果仍然是"静态的",因为您在前端存储了一组静态的问题。如果你想让它真正动态,你必须将问题和所有相关的细节存储在某种数据库中。