javascript - 单击按钮时选择框出现/消失

标签 javascript html

搜索了一下,没有找到我要找的东西。我有两个按钮,单击一次即可拉出两个不同的选择框,第二次单击它们就会消失。但是,我希望选择框 1 在单击按钮 2 时消失,反之亦然:选择框 2 将在单击按钮 1 时消失。

HTML:

window.onload = function() 
	  { 
      document.getElementById('name1').style.display = 'none';
      document.getElementById('name2').style.display = 'none';
	  };


	  function button1function(id){

      if(document.getElementById(id).style.display == 'none'){
         document.getElementById(id).style.display = 'initial';
      }else{
         document.getElementById(id).style.display = 'none';
      }
      }
	  function button2function(id){
      if(document.getElementById(id).style.display == 'none'){
         document.getElementById(id).style.display = 'initial';
      }else{
         document.getElementById(id).style.display = 'none';
      }
      }
<button type="button" value='hide/show' onclick="button1function('name1')">Button 1</button>
<button type="button" value='hide/show' onclick="button2function('name2')">Button 2</button>

    <select id="name1">
     <option value="">What would you like to know..</option>
    </select>
    <select id="name2">
     <option value="">What would you like to know 2..</option>
    </select>

最佳答案

像这样吗? https://jsfiddle.net/o3btLkpd/

尝试在按钮 1 的事件处理程序顶部调用此函数:

document.getElementById('name2').style.display = 'none';

这在按钮 2 的处理程序中:

document.getElementById('name1').style.display = 'none';

完整的结果代码如下所示:

  window.onload = function() { 
    document.getElementById('name1').style.display = 'none';
    document.getElementById('name2').style.display = 'none';
  };


  function button1function(id) {
    document.getElementById('name2').style.display = 'none';
    if (document.getElementById(id).style.display == 'none') {
       document.getElementById(id).style.display = 'initial';
    } else {
     document.getElementById(id).style.display = 'none';
    }
  }

  function button2function(id) {
    document.getElementById('name1').style.display = 'none';
    if (document.getElementById(id).style.display == 'none') {
       document.getElementById(id).style.display = 'initial';
    } else {
      document.getElementById(id).style.display = 'none';
    }
  }

关于javascript - 单击按钮时选择框出现/消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55170540/

相关文章:

html - 为什么div不在两个div之间

javascript - 保存在运行 html 时所做的更改(在浏览器中)

javascript - 在表中的 <i> 元素上弹出

javascript - 我们可以使用 Google Closure Compiler 从完整的 .js 文件创建 externs 吗?

javascript - 在 JavaScript 正则表达式中替换包含 $and 的字符串

javascript - MongoDB 外壳 : Query BinData by Type

当 html 和 body 自动溢出时,jquery scrollTop 不起作用

jquery - Flash 播放器位于 div 之外(仅在 IE 中)

javascript - 错误 : Can't set headers after they are sent in express-fileupload

javascript - Backbone View 有问题