让复选框显示某些内容

Having check boxes display certain things?

本文关键字:复选框 显示      更新时间:2023-09-26

完全不知道如何做到这一点或从哪里开始。但是,我想使用jQuery。

我想要一个大约 300 个项目的清单。每个项目都从一个类别分配到几个不同的类别。

例如:

项目:

香蕉橘子奶酪蛋糕

类别

水果黄色棕色橙甜点

这些项目将按如下方式分配:

香蕉 - 黄色, 水果

橙子 - 橙子,水果

奶酪 - 黄色

蛋糕 - 棕色, 甜点

.

我需要能够勾选复选框的任意组合 - 例如,如果我勾选"黄色和水果",它会显示橙子、香蕉和奶酪。(请注意,我需要所有黄色的东西加上所有水果,而不仅仅是黄色水果)。或者如果我只勾选黄色,它会显示奶酪和香蕉。如果我勾选甜点和橙子,它会显示蛋糕和橙子。希望你能理解我的意思。

我非常感谢任何关于如何实现这一目标的见解或帮助,谢谢。

我会创建一个对象数组,其中每个对象都有一个name属性和一个categories属性,该属性是一个字符串数组,其中每个字符串都是对象所属的类别名称。然后,您可以选中选中哪些类别复选框,然后遍历所有对象,仅显示在其"类别"属性中具有所有选定类别的对象。您可以通过创建具有所选对象属性的循环元素来显示它们。您可以使用for循环中找到正确的对象for如下所示:

伪代码:

//loop through the array of objects
//    for ever element, loop through its `categories` property and check if
//    it has the current element in the array of selected categories 
//    (`selected`). Then, do that for every element in `selected`

我知道这可能看起来令人困惑,如果是这样,我深表歉意,但我希望它有所帮助。

Matt B.由于您是Web开发的新手,因此让我告诉您一个解决方案,根据我的经验,我认为该解决方案可能最适合您,因此就在这里。你是Web开发的新手,所以我建议你现在不要使用MySql作为数据库,而使用PHP作为逻辑基础......所以我认为你必须专注于HTML,CSS和JS,现在让我指导你如何实现这个目标,要点是......1. 创建一个结构如下的 html 文件

<input class="yFruit" type="checkbox" value="YellowFruit"> Yellow Fruit<br>
<input class="rFruit" type="checkbox" value="RedFruit"> Red Fruit<br>
<div class="itemsContainer">
    <div class="item" data-category="YellowFruit"> Banana </div>
    <div class="item" data-category="RedFruit"> Apple </div>
</div>
  1. 使用 Css 根据需要设置这些元素的样式

  2. 现在是Javascript的时候了

你知道javascripts事件在这种情况下非常有用,比如当我点击某些东西时,我可以检测到我点击的elemenet是什么。就像当我们选择使用 html 创建的复选框之一时一样,我们可以看到它与所有元素匹配的值(在这种情况下,所有水果都带有 class="item"),我们可以为每个项目添加 css 属性,就像如果我们想隐藏一些元素,我们现在可以这样做,现在让我们看看代码。

// JS Code
// assigning all the checkbox in variables
var yFruit = document.querySelector(".yFruit");
var rFruit = document.querySelector(".rFruit");
// allItems is an array containing all the item elements in it
var allItems= document.querySelectorAll(".item");
// creating a function to only show the yFruit
 function showYFruitOnly(){
    for (i = 0; i < allItems.length; i++) {
        if(allItems[i].getAttribute("data-category") == "YellowFruit"){
            // display only if it is from yellow fruit category
            allItem[i].style.display = "block";
        }else{
            // do not display if it is not from that category  
            allItem[i].style.display = "none";
        }
    }
 }
// code below this line is checking if yFruit is checked or not 
//every time some one clicks on it
// if it is checked then the code is running
yFruit.onchange = function(){
if(yFruit.checked == true){
    // running the showYFruitOnly function if checkbox is checked
    showYFruitOnly;
}
}

您可以为更多案例等创建更多功能等尝试这个,我敢打赌你会学到很多东西......