在关于 HTML / CSS / jQuery的一些示例和教程之后,我设法创建了几个按钮,这些按钮将根据按下的按钮切换一些内容.我相信通过索引元素标识符或类似的想法,可以更有效/更有效地编写以下代
我特意寻找使用jQuery(和Bootstrap)的改进.
$(document).ready(function() { $("#button1").click(function() { $("#div1").show(); $("#div2").hide(); $("#div3").hide(); $("#div4").hide(); }); $("#button2").click(function() { $("#div1").hide(); $("#div2").show(); $("#div3").hide(); $("#div4").hide(); }); $("#button3").click(function() { $("#div1").hide(); $("#div2").hide(); $("#div3").show(); $("#div4").hide(); }); $("#button4").click(function() { $("#div1").hide(); $("#div2").hide(); $("#div3").hide(); $("#div4").show(); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <div class="container"> <h2>Button group</h2> <div class="btn-group"> <button id="button1" type="button" class="btn btn-primary">Div 1</button> <button id="button2" type="button" class="btn btn-primary">Div 2</button> <button id="button3" type="button" class="btn btn-primary">Div 3</button> <button id="button4" type="button" class="btn btn-primary">Div 4</button> </div> <div class="div-group"> <div id="div1" style="background-color: red;">div 1</div> <div id="div2" style="background-color: blue;">div 2</div> <div id="div3" style="background-color: red;">div 3</div> <div id="div4" style="background-color: blue;">div 4</div> </div> </div>您可以使用单击按钮的index()1来选择具有相同索引的id的div,并隐藏其兄弟.
$('.btn-group button').click(function() { $('.div-group #div' + ($(this).index() + 1)).show().siblings().hide() })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="container"> <h2>Button group</h2> <div class="btn-group"> <button id="button1" type="button" class="btn btn-primary">Div 1</button> <button id="button2" type="button" class="btn btn-primary">Div 2</button> <button id="button3" type="button" class="btn btn-primary">Div 3</button> <button id="button4" type="button" class="btn btn-primary">Div 4</button> </div> <div class="div-group"> <div id="div1" style="background-color: red;">div 1</div> <div id="div2" style="background-color: blue;">div 2</div> <div id="div3" style="background-color: red;">div 3</div> <div id="div4" style="background-color: blue;">div 4</div> </div> </div>