【问题标题】:How can I add category more than one如何添加多个类别
【发布时间】:2022-10-12 21:27:39
【问题描述】:

我正在尝试制作一个电影网站,并添加了一些类别。但是你知道电影/连续剧没有一个类别。我需要添加多个。我试着做category: "Mind-Bending","Ominous", 它没有用。

const posters = [
{
    title: "Dark",
    category: "Mind-Bending",
    img: "https://i.hizliresim.com/kl5ikc6.png",
    desc: `A family saga with a supernatural twist, set in a German town where the disappearance of two young,
    children exposes the relationships among four families.`
}]

const btnContainerDOM = document.querySelector(".categorie-cont")
const moviesContainerDOM = document.querySelector(".movies")
const btnList = ["All","Mind-Bending","Chilling","Ominous"]

btnList.forEach((value) => {
  let button = document.createElement("button")
  button.innerHTML = value
  button.setAttribute("data-id",value)
  button.addEventListener("click",buttonClick)
  btnContainerDOM.append(button)
})

function buttonClick(){
  const result = (this.getAttribute("data-id") === "All") ? posters : posters.filter((item) 
=> {
    return item.category == this.getAttribute("data-id")
});
addMovie(result) 
}

【问题讨论】:

  • 如果您希望您的类别包含多个类别,那么您只需将 category 定义为一个可以包含 0 到多个类别的数组。
  • 您也应该共享您的 HTML。这可以帮助你了解你在苦苦挣扎
  • 我不明白该怎么做
  • 应该使用类别作为数组并使用逻辑来检查您的对象项目子类别列表是否在主类别列表中

标签: javascript


【解决方案1】:
function buttonClick() {
var i, j;
const result = (this.getAttribute("data-id") === "All") ? posters : posters.filter((item) => {
    for (i = 0; i < posters.length; i++) {
        for (j = 0; j < posters[i].category.length; j++) {
            return item.category[j] == this.getAttribute("data-id")
        }
    }
});
addMovie(result)

}

我这样做了,但它仍然没有用

【讨论】:

  • 我在类别中添加了“动作”,但它只显示第一个类别
【解决方案2】:

.includes() 检查您的数组或字符串是否包含子字符串。在您的情况下,您想检查 category 的数组是否包含所选类别。

function buttonClick(){
  const dataId = this.getAttribute("data-id");

  const result = dataId === "All" ? posters : posters.filter((item) => {
    return item.category.includes(dataId);
  });

  addMovie(result) 
}

【讨论】:

    【解决方案3】:

    所以如果你想拥有更多的类别,你可以在posters 中定义category 为几个类别的Array,如下所示:

    const posters = [
    {
        title: "Dark",
        category: ["Mind-Bending", "Chilling"],
        img: "https://i.hizliresim.com/kl5ikc6.png",
        desc: `A family saga with a supernatural twist, set in a German town where the disappearance of two young,
        children exposes the relationships among four families.`
    }]
    

    自然,这意味着您需要稍微调整您的代码。

    【讨论】:

    • 我也这样做了。但我不知道如何更改我的代码:(
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-04
    • 1970-01-01
    • 2012-03-16
    • 1970-01-01
    • 1970-01-01
    • 2012-01-18
    • 1970-01-01
    相关资源
    最近更新 更多