【问题标题】:How to add a like to something but only once using local storage?如何添加一个喜欢的东西,但只使用本地存储一次?
【发布时间】:2022-01-12 22:17:43
【问题描述】:

我正在使用 API,我需要显示电影并喜欢它们,但我需要喜欢它们一次。我试图添加一个布尔值,我有这样的东西:

let beenLiked = false;

const movieLike = document.getElementById("likeButton")
movieLike.addEventListener('click', () => {
    console.log("ok like")
    axios.patch(`myUrl`)
    beenLiked = true
}, true)

问题是当我喜欢一部电影时,由于我的布尔值,我不能喜欢另一部电影,我该如何修改它来解决我的问题?

【问题讨论】:

  • 这取决于您希望如何跟踪喜欢。你有用户系统吗?如果没有,您是否跟踪 IP?喜欢不喜欢不止一次的限制是什么。你有多人吗?然后,您应该明确地在您的数据库或保存喜欢的任何地方跟踪它,并将那里的人保存在一个数组中。调用 api 后,通过在数组中查找匹配项来检查请求者是否已经喜欢这部电影。然后拒绝该动作,如果它已经被喜欢。或者您可以禁用 eventListener (虽然将在页面重新加载时重新激活:/)
  • @MaximilianDolbaum 问题是我们没有任何数据库,我们只是有能够喜欢电影的指令,以任何方式存储它以使电影不受欢迎。

标签: javascript local-storage addeventlistener


【解决方案1】:

如果您可以获取应该喜欢的电影的名称(我没有您的 html 文件可以为您做),您可以跟踪名称并这样做:

let beenLiked = []

const movieLike = document.getElementById("likeButton")
movieLike.addEventListener('click', () => {
    const movie = "The Movie" // Get the movie name or id which has to be liked
    if(beenLiked.indexOf(movie) === -1){
        console.log("ok like")
        axios.patch(`myUrl`)
        beenLiked.push(movie)
        return true
    }
    console.log("Already liked once")
    return false
})

这里是没有html的简化版:

let beenLiked = []

function a() {
  const movie = "The Movie" // Get the movie the likeButton is attached to
  if (beenLiked.indexOf(movie) === -1) {
    beenLiked.push(movie)
    return true
  }
  return false
}
console.log(a())
console.log(a())

【讨论】:

  • 所以我尝试运行你的代码,经过一些小的修改后我运行它,我得到一个控制台错误说:Cannot read properties of null (reading 'indexOf') at HTMLDivElement.
  • 在学校你的代码运行良好,但现在我在家我不再工作了,我不知道为什么
猜你喜欢
  • 2015-02-04
  • 2019-08-13
  • 2011-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-14
  • 1970-01-01
相关资源
最近更新 更多