【问题标题】:How to add filter in a Pug form?如何在 Pug 表单中添加过滤器?
【发布时间】:2021-10-18 11:44:11
【问题描述】:

这是我的数据库示例

我正在使用 nodejs、MongoDB 和 pug 创建一个网站。我以哈巴狗的形式显示了这些数据,数据在选择框中。像这样,但在哈巴狗中使用 for 循环和所有数据-

<!DOCTYPE html>
<html>
  <body>
    <form>
      <select name="Type">
        <option value="Electronic">Electronic</option>
      </select>
         
      <select name="Brands">
        <option value="Apple">Apple</option>
        <option value="Dell">Dell</option>
        <option value="Samsung">Samsung</option>
      </select>
      
      <select name="Products">
        <option value="Macbook Pro">Macbook Pro</option>
        <option value="Inspioren">Inspioren</option>
        <option value="Galaxy S20">Galaxy S20</option>
      </select>
    </form>
  </body>
</html>

我想做的是,根据用户在其他选择选项中选择的内容更改选择框选项。

例如:- 如果用户选择"Type: "Electronic", and "Brand: Apple",我只想显示 Apple 产品作为选项。 或者如果用户选择"Type: "Electronic",它应该会自动在品牌选择框中显示品牌列表。

数据将从数据库中添加(不会被硬编码)。

【问题讨论】:

    标签: javascript node.js pug


    【解决方案1】:

    一种可能是修改您的 Pug 视图以包含 select 标记 ID 并将下游选择留空,然后在视图末尾添加一个脚本以添加事件侦听器并使用 JQuery 或仅使用 javascript 进行一些 DOM 操作加载视图后。然后,事件处理程序将允许您根据您在当前标签中选择的任何内容有条件地填写您的下一个 select 标签。

    类似的东西:

    script.
      document.addEventListener("DOMContentLoaded", 
      function(e) {
        const typeSelect = document.getElementById('type')
        typeSelect.onchange = function(e) {
          const brandSelect = document.getElementById('brand')
          if (typeSelect.options[typeSelect.selectedIndex].text === 'Apple') {
            ['MacBook Pro', 'MacBook Air', 'MacBook Mini'].forEach(function(product) {
              let newOption = createElement('option')
              newOption.textContent = product
              brandSelect.appendChild(newOption
           }
           else if ( // etc... ) {}
           else {
           // functionality to clear out the downstream select tags.
           }
        }
    
        const brandSelect = document.getElementById('brand')
        brandSelect.onchange = // etc, etc....
    
      })
    

    【讨论】:

    • 我试图运行上面的代码,但它没有工作甚至在我的文件中运行。
    【解决方案2】:

    服务器端代码,带有一些测试数据:

    app.get("/avi", (req, res) => {
      res.render("avi", { Types: [ "Electronic"], data: 
        [ { Type: "Electronic", Brand: "Apple", Products: [ "MacBook Pro", "MacBook Air", "Mac Mini"]}, 
          { Type: "Electronic", Brand: "Dell", Products: [ "Inspioren", "Latitude"]},
          { Type: "Electronic", Brand: "Samsung", Products: [ "Galaxy S20", "Galaxy S10"]}
        ]
      });
    });
    

    您应该包含一个类型列表,否则您的 Pug 脚本将不得不通过原始数据来识别唯一类型的数量。

    avi.pug:

    html
      head
      body 
        p Linked Dropdowns
        form
          p Type: 
            select#types(onchange="typeChanged()")
              option(value="") Select Type
              each item of Types 
                option(value=item)=item
          p Brand:
            select#brands(onchange="brandChanged()")
              option(value="") Select Brand
          p Product:
            select#products()
              option(value="") Select Product
    
      script.
        const data = JSON.parse(`!{JSON.stringify(data)}`);
        const types = document.getElementById("types")
        const brands = document.getElementById("brands")
        const products = document.getElementById("products")
    
        const typeChanged = () => {
          clearBrands(); clearProducts();
          if (types.selectedIndex!==0) {
            const selectedType = types.options[types.selectedIndex].text;
            data.forEach(d => {
              if (d.Type===selectedType) {
                const newBrand = document.createElement("option")
                newBrand.value = newBrand.innerText = d.Brand;
                brands.appendChild(newBrand);
              }
            });
          }
        }
        const brandChanged = () => {
          clearProducts();
          if (brands.selectedIndex!==0) {
            const selectedType = types.options[types.selectedIndex].text;
            const selectedBrand = brands.options[brands.selectedIndex].text;
            data.forEach(d => {
              if (d.Type===selectedType && d.Brand===selectedBrand) {
                d.Products.forEach(p => {
                  const newProd = document.createElement("option")
                  newProd.value = newProd.innerText = p;
                  products.appendChild(newProd);
                });
              }
            })
          }
        }
    
        const clearBrands = () => {
          const item0 = brands.childNodes[0];
          brands.textContent = ""; 
          brands.appendChild(item0);
        }
        const clearProducts = () => {
          const item0 = products.childNodes[0];
          products.textContent = ""; 
          products.appendChild(item0);
        }
    

    服务器上的data被注入到客户端Javascript中:

    const data = JSON.parse(`!{JSON.stringify(data)}`);
    

    这种方法不是很健壮。如果数据中的任何地方有反引号`字符,就会出现问题。

    【讨论】:

      【解决方案3】:

      我在这里回答我自己的问题。我所做的是在类型选择框中添加onchange 函数。并在我的文件中创建了一个脚本,使用以下代码-

      function change() {
                          var Type_name = document.getElementById("type").value;
                          var Brand= document.getElementById('brands');
                          var Product = document.getElementById('products');
                          Brand.options.length = 0;
                          Product.options.length = 0;
      
                          var DefaultBrand = new Option("Brand", "Null");
                          var DefaultProduct = new Option ("Product", "Null");
                          Brand.add(DefaultBrand, undefined);
                          Product.add(DefaultProduct, undefined);
      
                          var product_master = !{JSON.stringify(product_names)};
      
                          for (const brands of product_master) {
                              if (brands.Type == Type_name){
                                  const BrandOption = new Option(brands.Brand, brands.Brand);
                                  Brand.add(BrandOption, undefined);
                              }
      
                          }
                      
      

      还有一个类似的添加产品的功能。

      这对我有用。但如果有人想改进此代码,我将不胜感激。

      【讨论】:

        猜你喜欢
        • 2020-10-07
        • 1970-01-01
        • 1970-01-01
        • 2017-02-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-02-21
        • 2017-09-06
        相关资源
        最近更新 更多