HTML-JS:按钮的Plethora,每个按钮产生不同的形式

时间:2019-07-28 19:13:42

标签: javascript html forms button

在我的主页上,我希望有过多的按钮(至少四个),每个按钮都将生成一个表单,每个表单具有不同的操作。

在任何时候,只有一种形式可见。

最好的方法是什么?

我应该创建四种形式吗?当选择一个按钮时,其他所有形式都将用"visibility=hidden"并公开我想要的形式吗?

1 个答案:

答案 0 :(得分:0)

“最佳方法”显然是主观的。
也就是说,请注意,设置style.visibility = "hidden"使元素不可见,但在页面上为其留有空白。
对于更干净的UI,您可能需要使用style.display = "none"


下面建议的解决方案的算法是:

---从所有隐藏的表单开始(使用CSS)  ---听文档中的所有点击。
 ---只要单击以与表单相关的按钮之一为目标,
 -------遍历所有表单,并针对每种表单:
 ----------隐藏表单。
 ----------将表单的id属性与(单击的)按钮的data-form属性进行比较。
 ----------如果表单与按钮匹配,请再次显示该表单。


const forms = document.querySelectorAll("form"); // Remembers a list of all the forms

document.addEventListener("click", changeForm); // Runs the function on clicks

function changeForm(event){

  // Makes sure a form button was clicked before proceding
  if(event.target.classList.contains("formBtn")){

    // Remembers which button was clicked
    const formBtn = event.target;
    
    // Converts the `forms` NodeList to an Array so we can use the `.forEach` method
    const formsArray = Array.from(forms);    

    // `forEach` takes one argument: a function that we provide using `=>` notation.
    //    Our function (which `forEach` calls once for EACH form in `formsArray`)
    //    gets each form as an argument, hides the form, then possibly reveals it again
    formsArray.forEach(form =>{
      form.style.display = "none"; // Hides the current form

      // Relies on the button's `data-form` attribute matching the form's `id`
      if(form.id == formBtn.dataset.form){
        // Reveals the current form if it matches the button
        form.style.display = "block";
      }
    });
  }
}
form{ height: 2em; width: 20em; border: 1px solid gray; display: none; }
<div>
  <div is="buttonsContainer">
    <button data-form="form1" class="formBtn">Form 1</button>
    <button data-form="form2" class="formBtn">Form 2</button>
    <button data-form="form3" class="formBtn">Form 3</button>
    <button data-form="form4" class="formBtn">Form 4</button>
  </div>
  <div id="formsContainer">
    <form id="form1">This is Form 1</form>
    <form id="form2">This is Form 2</form>
    <form id="form3">This is Form 3</form>
    <form id="form4">This is Form 4</form>
  </div>
</div>