【发布时间】:2020-09-27 04:05:45
【问题描述】:
我想创建一个循环而不是为每个元素添加 JavaScript 以在第一次点击时显示 div 并在第二次点击时隐藏 div。
单击第一个 div 时只会显示第一个 div,单击第二个 div 时会显示第二个 div,我不想在单击其他元素时隐藏任何 div。
我想在点击时显示div,并在第二次点击时隐藏它。
$(".d01").click(function() {
$(".desc1").toggle();
});
$(".d02").click(function() {
$(".desc2").toggle();
});
$(".d03").click(function() {
$(".desc3").toggle();
});
$(".four").click(function() {
$(".d04").toggle();
});
$(".d05").click(function() {
$(".desc5").toggle();
});
$(".d06").click(function() {
$(".desc6").toggle();
});
$(".d07").click(function() {
$(".desc7").toggle();
});
$(".d08").click(function() {
$(".desc8").toggle();
});
$(".d09").click(function() {
$(".desc9").toggle();
});
$(".d010").click(function() {
$(".desc10").toggle();
});
$(".d011").click(function() {
$(".desc11").toggle();
});
$(".d012").click(function() {
$(".desc12").toggle();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="d01 topic1">Safety</button>
<button type="button" class="d02 topic2">Environment</button>
<button type="button" class="d03 topic3">Climate change</button>
<button type="button" class="d04 topic4">Sustainability</button>
<button type="button" class="d05 topic5">Business strategy</button>
<button type="button" class="d06 topic6">Performance data</button>
<button type="button" class="d07 topic7">Working for You</button>
<button type="button" class="d08 topic8">Working together</button>
<button type="button" class="d09 topic9">Social performance</button>
<button type="button" class="d010 topic10">Human rights</button>
<button type="button" class="d011 topic11">Special reports</button>
<button type="button" class="d012 topic12">Key topics</button>
<div class="desc desc1">Safety</div>
<div class="desc desc2">Environment</div>
<div class="desc desc3">Climate change</div>
<div class="desc desc4">Sustainability</div>
<div class="desc desc5">Business strategy</div>
<div class="desc desc6">Performance data</div>
<div class="desc desc7">Working for You</div>
<div class="desc desc8">Working together</div>
<div class="desc desc9">Social performance</div>
<div class="desc desc10">Human rights</div>
<div class="desc desc11">Special reports</div>
<div class="desc desc12">Key topics</div>
【问题讨论】:
-
最好是为所有这些元素添加一个 CSS 类,这对它们来说是通用的。否则,您可以使用逗号对“.one, .two, .three”进行 jQuery 选择。
标签: javascript jquery