繁体   English   中英

动态添加时如何使 materializecss 下拉列表工作

[英]How to make the materializecss dropdown work when added dynamically

以下是我在Google Apps Script中制作的示例网络表单示例,我试图在单击add按钮时动态添加三个 select 下拉菜单和一个输入元素。 元素应按以下顺序呈现 - dropdown dropdown input dropdown

我正在为此使用物化框架

经过大量尝试和阅读materializecss文档后,我能够按预期呈现文本输入字段 但是,下拉菜单仍然不会呈现。 显然,我犯了一些错误,无法弄清楚是什么和在哪里。

我包括代码文件-

  1. Code.gs
function doGet(e) {
  Logger.log(e);
  return HtmlService.createTemplateFromFile('form_materialize').evaluate();
}

function include(fileName){
  return HtmlService.createHtmlOutputFromFile(fileName).getContent();
}
  1. form_materialize.html
<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <!-- google font pack link -->
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <!-- Mini materialize.css cdn link -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
    <?!= include('css_scripts'); ?>
  </head>
  <body>
    <div class="container">
      
      <div class = "row">
        <h1>A Sample Form</h1>
      </div>
      
      <div id="productsection">
        <!-- product details like "Product Type"(dropdown), "Products"(dropdown), "Product Qty"(text input field), "Unit"(dropdown) to be added here dynamically -->

      </div>

      <div class = "row">
        <a class="btn-floating btn-large waves-effect waves-light red" id="addproduct"><i class="material-icons">add</i></a>
      </div> 

    </div>
    <!-- Mini materialize.js cdn link -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
    <?!= include('js_scripts_materialize'); ?>
  </body>
</html>
  1. js_scripts_materialize.html
<script>
  document.addEventListener('DOMContentLoaded', function() {
    var elems = document.querySelectorAll('select');
    var instances = M.FormSelect.init(elems, options);
  });

  let counter = 0;

  const orderTypeList = ["PH", "ECOM"];
  const optionList = ["Test Product 1", "Test Product 2", "Test Product 3", "Test Product 4", "Test Product 5"];                                   
  const unitOptionList = ["KGS", "PCS", "BAGS"];
  
  document.getElementById("addproduct").addEventListener("click", addInputField);

  function addInputField(){
    counter++;
    
    // everytime when "add product" button is clicked, the following elements must be added to the "<div id="produc></div>" tag.

    // <div class="row">
    //  <div class="input-field col s4" id="divone">
      //   <select id="productX">
      //     <option>option-i</option>
      //     <option>option-1</option>
      //     <option>option-2</option>
      //     ...
      //     ...
      //     <option>option-n</option>
    //     <select>
    //  </select>
    //  <div class="input-field col s4" id="divtwo"> 
    //     <input id="productqtyX" type="text">
    //     <label for="productqtyX">Quantity</label>
    //  </div>
    //  <div class="input-field col s4" id="divthree"> 
    //     <select id="productUnitX">
    //       <option>option-1</option>
    //       <option>option-2</option>
    //       ...
    //       ...
    //       <option>option-n</option>
    //     </select>
    //  </div>
    // </div>
    
    // creates a new div of class row
    const newDivElem = createElementTemplate('div', null, ['row']);

    // creates a new select tag for order type dropdown
    const newOrderTypeSelectElem = createElementTemplate('select', "ordertype" + counter.toString());

    // generates the content of the dropdown for products and is inserted to the above "productX" select tag
    createOptionsElem(newOrderTypeSelectElem, orderTypeList);

    // creates a new select tag for product dropdown
    const newProductSelectElem = createElementTemplate('select', "product" + counter.toString());

    // generates the content of the dropdown for products and is inserted to the above "productX" select tag
    createOptionsElem(newProductSelectElem, optionList);

    // creates a input element for quantity input
    const newQtyInputElem = createElementTemplate('input', 'productqty' + counter.toString(), ['validate']);
    newQtyInputElem.type = 'text';

    // creates a label for the quantity input element
    const newQtyLabelElem = createElementTemplate('label');
    newQtyLabelElem.textContent = "Quantity";

    //Creates a new select element for product quantity unit(dropdown)
    const newUnitSelectElem = createElementTemplate('select', 'productqtyunit' + counter.toString());

    // generates the content of the dropdown for units and is inserted to the above "productqtyunitX" select tag
    createOptionsElem(newUnitSelectElem, unitOptionList);

    //create inner "div" tags with class "input-field col s4" as described in materializecss documentation
    const innerDivElems = [];

    for(let i = 0; i < 4; i++){
      innerDivElems.push(createElementTemplate('div', `div${(Number(i) + 1)}`, ['input-field', 'col', 's3']));
    }
    
    innerDivElems[0].appendChild(newOrderTypeSelectElem);

    innerDivElems[1].appendChild(newProductSelectElem);

    innerDivElems[2].appendChild(newQtyInputElem);
    innerDivElems[2].appendChild(newQtyLabelElem);

    innerDivElems[3].appendChild(newUnitSelectElem);

    //Inserts select, quantityInput, quanityLabel, newUnitSelectTag tags in div child
    for(let i in innerDivElems){
      newDivElem.appendChild(innerDivElems[i]);
    }

    // Finally, appends the newly created div tag to the productSection tag.
    document.getElementById('productsection').appendChild(newDivElem);
  }

function createOptionsElem(selectElem, optionsArr){
  const newDefaultOptionElem = document.createElement('option');
  newDefaultOptionElem.disabled = true;
  newDefaultOptionElem.setAttribute('selected', true);
  newDefaultOptionElem.textContent="Choose your option";

  selectElem.appendChild(newDefaultOptionElem);

  for(let i in optionsArr){
    const newOptionElem = document.createElement('option');
    newOptionElem.textContent = optionsArr[i];
    newOptionElem.value = optionsArr[i];

    // Inserts the option tag in select tag
    selectElem.appendChild(newOptionElem);
  }
}

// function to create a new element
function createElementTemplate(tagType, idVal, classNameList){
  const newElement = document.createElement(tagType);
  
  if(idVal !== undefined)
    newElement.id = idVal;
  
  if(classNameList !== undefined){
    for(let i in classNameList){
      newElement.classList.add(classNameList[i]);
    }
  }

  return newElement;
}
</script>

虽然我不确定我是否能正确理解你的预期结果,但下面的修改呢?

本次修改,修改了你的js_scripts_materialize.html

修改脚本:

我认为在这种情况下,这部分可能不需要使用。

document.addEventListener('DOMContentLoaded', function() {
  var elems = document.querySelectorAll('select');
  var instances = M.FormSelect.init(elems, options);
});

另外,请按如下方式修改addInputField()

从:

document.getElementById('productsection').appendChild(newDivElem);

到:

document.getElementById('productsection').appendChild(newDivElem);
var elems = document.querySelectorAll('select'); // Added
M.FormSelect.init(elems); // Added
  • 通过这个修改,我认为当你点击一个红色按钮时,你可以看到下拉列表。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM