有没有办法动态使用jquery的toggle()?

编辑:


我想制作一个 div,里面有一些 div。我想切换该 div ,当我单击其中一个按钮时,我想消失不匹配的 div 并显示匹配的 div 。这是我的代码:


<div class="TheToggle">

    <button id="Toggle1">Toggle 1</button>

    <button id="Toggle2">Toggle 2</button>

    <button id="Toggle2">Toggle 3</button>



    <div class="Toggle1">This 1</div>

    <div class="Toggle2">This 2</div>

    <div class="Toggle3">This 3</div>

</div>

实际上,一开始我想显示 Toggle1 内容,当我单击另一个按钮时,我想出现该按钮的 div 并消失另一个按钮。


牛魔王的故事
浏览 45回答 1
1回答

眼眸繁星

let buttons = document.querySelectorAll('.TheToggle button');buttons.forEach(b => {&nbsp; &nbsp; b.addEventListener('click', () => {&nbsp; &nbsp; &nbsp; &nbsp; document.querySelectorAll('.TheToggle > div')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.forEach(d => d.style.display = 'none');&nbsp; &nbsp; document.querySelector(`[data-hide="${b.getAttribute('id')}"]`).style.display = 'block';&nbsp; })&nbsp; &nbsp;&nbsp;});<div class="TheToggle">&nbsp; &nbsp; <button id="Toggle1">Toggle 1</button>&nbsp; &nbsp; <button id="Toggle2">Toggle 2</button>&nbsp; &nbsp; <button id="Toggle3">Toggle 3</button>&nbsp; &nbsp; <div data-hide="Toggle1">This 1</div>&nbsp; &nbsp; <div data-hide="Toggle2">This 2</div>&nbsp; &nbsp; <div data-hide="Toggle3">This 3</div></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5