【问题标题】:Show/Hide Divs from Dropdown从下拉菜单中显示/隐藏 div
【发布时间】:2021-03-10 09:14:44
【问题描述】:

这个真的很简单,但我不知何故无法理解它。

我有一个包含 3 个选项的引导下拉菜单。

我的页面将托管 3 个默认隐藏的 div。

当点击下拉菜单中的一个选项时,我希望相关的 div 出现。

HTML:

<div class="dropdown d-flex justify-content-center">
    <button class="btn bg-dark text-light dropdown-toggle rounded-bottom" style="border-radius: 0 !important;" type="button" id="dropdownMenu2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                Secure Acceptance Silent Order POST / Checkout API</button>
    <div id="target" class="dropdown-menu" aria-labelledby="dropdownMenu2">
        <button value="1" class="master dropdown-item" type="button">Auth/Sale using Transaction Endpoint</button>
        <button value="2" class="master dropdown-item" type="button">Auth/Sale using iFrame Transaction Endpoint</button>
        <button value="3" class="master dropdown-item" type="button">Auth/Sale with Token Creation</button>
    </div>
</div>
        
<div id="1" class="SAformX hidden" style="background-color:red;">
    <p>gergeyherghdesghderh</p>
</div>
<div id="2" class="SAformY hidden" style="background-color:blue;">
    <p>gergeyherghdesghderh</p>
</div>
<div id="3" class="SAformZ hidden" style="background-color:green;">
    <p>gergeyherghdesghderh</p>
</div>

默认情况下,隐藏类的表单是隐藏的:

<style>
    .hidden{
        visibility: hidden;
    }
</style>

使用 Vanilla Javascript,我想生成一个元素节点,其中包含与下拉列表中的每个按钮/选择相关的 Master 类。然后,我想将其相关 ID 传递给另一个函数:

  • 默认情况下所有 div 将重置为隐藏
  • 然后会出现ID与点击按钮相关的div。

这样,每次单击下拉选项时,页面“软重置”并隐藏所有未选择的 div。

Javascript:

<script>
document.addEventListener('DOMContentLoaded', function() {
document.querySelectorAll('.master').forEach(item => {
            item.addEventListener('click', () => {
                const id = item.value;
                MasterMenuToggle(id);
            });
        });
    })
function MasterMenuToggle(id) {

    document.querySelectorAll('.SAform').forEach(item => {
        item.className = "hidden";
    })
    document.getElementById(id).className = "visible"
}
</script>

这里的问题是我的功能 MasterMenuToggle 的“重置”部分

document.querySelectorAll('.SAform').forEach(item => {
    item.className = "hidden";
})

单击下拉项确实会显示其相关的 div,但随后它们会继续出现而没有其他隐藏。

  • 我还没有设置设计,因此“破坏/更改”类名会破坏我可能添加到它们的任何格式。它们确实出现是因为页面无法应用可见性:自类更改后隐藏。但是,如果我喜欢“class="hidden pt-2 border bg-black",那么 JS 会将 className 更新为“class="visible”,从而杀死其余的 Bootstrap 类。

为了安全起见,我可以遍历 ID 以简单地将内联 CSS 添加到每个 DIV 吗?

  • 我的 JS 代码重置部分中的 forEach 是阻止程序,会生成控制台错误。我不明白为什么即使 console.log(item) 而不是将 className 更改为 hidden 也不起作用。

希望你能帮忙!

【问题讨论】:

  • id 不能以数字开头,这会使您的 HTML 无效。另外我建议您使用hidden 属性,而不是使用您自己的CSS 类.hidden 重新创建它。这允许你做item.hidden = true;

标签: javascript html css


【解决方案1】:

您需要使用 classList.add 或 classList.remove 函数。

因此,如果要显示,请使用 remove 删除隐藏,否则使用 .add 再次隐藏。

例如item.classList.add("隐藏");或 item.classList.remove("hidden")

您可以使用 classList 执行很多操作,此处说明:

https://developer.mozilla.org/en-US/docs/Web/API/Element/classList

【讨论】:

    【解决方案2】:

    您使用了隐藏所有 div 的代码

    function MasterMenuToggle(id) {
        document.querySelectorAll('.SAform').forEach(item => {
            item.className = "hidden";
        })
    }
    

    但是您的 div 的类名是“SAformX”、“SAformY”和“SAformZ”。所以 querySelectorAll('.SAform') 找不到任何 div。您可以将“SAform”类名添加到隐藏的 div 中。

    *抱歉我的英语不好:/

    这是工作的 JSFiddle https://jsfiddle.net/7nf18dr6/3/

    【讨论】:

      【解决方案3】:

      hiddenDivs = document.querySelectorAll('.SAform');
      document.addEventListener('DOMContentLoaded', function() {
          hiddenDivs.forEach((x) => x.classList.add('.hidden'));
          document.querySelectorAll('.master').forEach((item) => {
              item.addEventListener('click', () => {
                  const id = item.value;
                  MasterMenuToggle(id);
              });
          });
      });
      function MasterMenuToggle(id) {
          hiddenDivs.forEach((x) => {
              if (x.id == id) {
                  x.classList.remove('hidden');
              } else {
                  x.classList.add('hidden');
              }
          });
      }
      .hidden {
          visibility: hidden;
      }
          <div class="dropdown d-flex justify-content-center">
              <button class="btn bg-dark text-light dropdown-toggle rounded-bottom" style="border-radius: 0 !important;" type="button" id="dropdownMenu2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                  Secure Acceptance Silent Order POST / Checkout API
              </button>
              <div id="target" class="dropdown-menu" aria-labelledby="dropdownMenu2">
                  <button value="1" class="master dropdown-item" type="button">Auth/Sale using Transaction Endpoint</button>
                  <button value="2" class="master dropdown-item" type="button">Auth/Sale using iFrame Transaction Endpoint</button>
                  <button value="3" class="master dropdown-item" type="button">Auth/Sale with Token Creation</button>
              </div>
          </div>
          
          <div id="1" class="SAform " style="background-color:red;">
              <p>gergeyherghdesghderh</p>
          </div>
          <div id="2" class="SAform " style="background-color:blue;">
              <p>gergeyherghdesghderh</p>
          </div>
          <div id="3" class="SAform " style="background-color:green;">
              <p>gergeyherghdesghderh</p>
          </div>

      【讨论】:

        【解决方案4】:

        如果你把它分成两个阶段,这个任务就很简单了。第一阶段是当点击三个按钮中的一个时隐藏所有div元素,然后分别根据按钮和div的valuedata-id显示相关的div。您可以使用内联声明 display='none' 而不是使用新类 (hidden),或者按照 @connexo 上面的建议,使用 hidden=true ~ 虽然我认为这些在页面上的表示方式有所不同一个不占空间,另一个会。

        document.querySelectorAll('div#target > button').forEach( bttn=>{
            bttn.addEventListener('click',function(e){
                let col=document.querySelectorAll('div[data-id]');
                    col.forEach( div=>{ div.style.display='none' } )
                    
                document.querySelector('div[ data-id="'+this.value+'"]').style.display='block'
            })
        })
        /* css here only to prettify things */
        div{ padding:0.25rem; color:white }
        button{padding:0.5rem;margin:0.25rem;}
        <div class="dropdown d-flex justify-content-center">
            <button class="btn bg-dark text-light dropdown-toggle rounded-bottom" style="border-radius: 0 !important;" type="button" id="dropdownMenu2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                Secure Acceptance Silent Order POST / Checkout API
            </button>
            
            <div id="target" class="dropdown-menu" aria-labelledby="dropdownMenu2">
                <button value="1" class="master dropdown-item" type="button">Auth/Sale using Transaction Endpoint</button>
                <button value="2" class="master dropdown-item" type="button">Auth/Sale using iFrame Transaction Endpoint</button>
                <button value="3" class="master dropdown-item" type="button">Auth/Sale with Token Creation</button>
            </div>
        </div>
        
        <!-- HTML element IDs cannot begin with a number, use a dataset attribute instead -->
        <div data-id=1 class="SAformX hidden" style="background-color:red;">
            <p>Red div - data-id=1</p>
        </div>
        
        <div data-id=2 class="SAformY hidden" style="background-color:blue;">
            <p>Blue div - data-id=2</p>
        </div>
        
        <div data-id=3 class="SAformZ hidden" style="background-color:green;">
            <p>Green div - data-id=3</p>
        </div>

        【讨论】:

          猜你喜欢
          • 2017-12-16
          • 2012-08-03
          • 2012-08-06
          • 1970-01-01
          • 2010-12-07
          • 1970-01-01
          • 2014-12-23
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多