【问题标题】:How can I detect if a var was passed and then block it from passing again?如何检测是否传递了 var 然后阻止它再次传递?
【发布时间】:2022-12-19 15:54:31
【问题描述】:

我有一个简单的问题,我的项目是一个快速的 4 个选项答案,显示单选按钮和图片,现在我将图片和答案存储在一个文本文件中,这样我的 JS 会检测它读取的内容,然后将其传递给 HTML ,现在我使用这个函数来随机选择一条线:

fetch('./Test.txt', {
  credentials: 'same-origin',
  mode: 'same-origin',
}) // reads the file  as a buffer
  .then(function(response) {
    return response.text();

  })
  .then(function(data) {

    a = data
    a = a.toString() // makes the buffer into a readable string
    a = a.split('\n') // makes all the items in the list
    randomNum = Math.floor(Math.random() * {The number of lines that you have in the text file}) // makes a math equation to get a random line from the text file

现在我如何检测randomNum是否通过了已经通过的行?或者比方说,我如何检查函数 randomNum 是否传递了已传递的行? 先感谢您

【问题讨论】:

  • 忘了提到 `a[randomNum]` 给你一个随机行。
  • @UsithaIndeewara,我要问的是,当我得到第 1 行时,它已显示/运行,我如何存储 cookie 以告诉 JS 该用户已获得第 1 行,并告诉 JS不再为该用户显示行号 1?
  • 抱歉,如果您不明白我的问题,我的问题是,我如何存储一个 cookie 来检查该用户是否得到了第 7 行,并且不再为用户显示它?

标签: javascript html node.js if-statement fetch


【解决方案1】:

您的客户端 Javascript 代码可以维护一组已经看到的图片并将其存储在 cookie 中。在你当前拥有randomNum = Math.floor(...)的地方,在你的function(data) {...}内执行以下语句:

var picturesSeen = JSON.parse((document.cookie || "a=[]").substring(2));
if (picturesSeen.length === a.length)
  alert("Sorry, no more pictures");
else {
  while (true) {
    var randomNum = Math.floor(Math.random() * a.length);
    if (picturesSeen.indexOf(randomNum) === -1) {
      picturesSeen.push(randomNum);
      break;
    }
  }
  document.cookie = "a=" + JSON.stringify(picturesSeen);
}

cookie 将在页面重新加载后继续存在。

您可以使用以下命令“重置”cookie

document.cookie = "a=[]";

【讨论】:

  • 具有重新加载页面功能会影响此 sn-p 代码吗?由于它是客户端,我没有调用上面的函数,我只是在页面加载时执行它然后刷新页面以获取新行,或者我应该在函数调用中进行它以便它至少可以存储 cookie?
  • 如果我的问题不清楚,这是整个项目的 Repl.it 模板,replit.com/@lolt04588/Template?v=1
  • 好的,非常感谢您的帮助,很高兴看到一个地方,您可以在遇到问题时随时获得帮助,我希望有一个“提示”功能,再次非常感谢,非常感谢。
  • 但最后一个问题,它会自动重置吗?或者我该如何休息呢?
  • 请参阅我的扩充答案。
猜你喜欢
  • 2015-03-04
  • 1970-01-01
  • 1970-01-01
  • 2012-05-28
  • 2017-05-05
  • 2015-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多