gpt4 book ai didi

javascript - 如果单击此选项 显示此选项 隐藏此选项

转载 作者:行者123 更新时间:2023-11-28 00:06:45 25 4
gpt4 key购买 nike

我在这里看到了其他 if else 示例,但没有专门解决 jquery“if clicked show this else hide this”。这是一个简单的代码示例。我想知道单击 #red 时显示 .redStuff 的最简洁方法,否则隐藏它并在单击相对 id 时显示其他类。这是 HTML:

.redStuff, .blueStuff, .greenStuff {
display: none;
}
<ul id="color">
<li id="red"><a href="#">Red</a></li>
<li id="blue"><a href="#">Blue</a></li>
<li id="green"><a href="#">Green</a></li>
</ul>

<div class="redStuff">Red Stuff</div>
<div class="blueStuff">Blue Stuff</div>
<div class="greenStuff">Green Stuff</div>

最佳答案

一旦掌握了想法,使用数据属性就很容易了。

CSS

.redStuff, .blueStuff, .greenStuff {
display: none;
}

html

<ul id="color">
<li id="red" data-color="red"><a href="#">Red</a></li>
<li id="blue" data-color="blue"><a href="#">Blue</a></li>
<li id="green" data-color="green"><a href="#">Green</a></li>
</ul>

<div class="redStuff" data-content="red">Red Stuff</div>
<div class="blueStuff" data-content="blue">Blue Stuff</div>
<div class="greenStuff" data-content="green">Green Stuff</div>

jquery

       // no need for the ids or classes
// we set data attributes for the html
$("li[data-color]").click(function(){
// next line is for second click, to hide the prev div element
$("div[data-content]").hide();
// we are getting the data-color attr value here
// and for readibility we assigned it to a variable called color
var color = $(this).data("color");
// find the div with the same content and show
$("div[data-content='"+color+"']").show();
});

jsfiddle link to play with codes

关于javascript - 如果单击此选项 显示此选项 隐藏此选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31281051/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com