两种状态的三向切换(JavaScript或jQuery) [英] Three-way toggling of two states (Javascript or jQuery)
问题描述
我正在处理一个页面,该页面将以多种货币(欧元,英镑或美元)显示价格.我的目标是首先显示欧元价格,而隐藏英镑和美元价格.
I am working on a page that will show prices in a choice of currencies (euros, pounds or dollars). My aim is to display the price in euros first, keeping the pound and dollar prices hidden.
<button id="mybutton">Change Currency</button>
<p id="euro" class="shown">Euro</p>
<p id="pound" class="hidden">Pound</p>
<p id="dollar" class="hidden">Dollar</p>
单击按钮时,我需要三个ID来循环显示/隐藏/隐藏,隐藏/显示/隐藏和隐藏/隐藏/显示三个状态. 到目前为止,我已经使用了两个id(不难!).
When the button is clicked, I need the three ids to cycle through the three states shown/hidden/hidden, hidden/shown/hidden and hidden/hidden/shown. So far I have made it work with two ids (not difficult!).
$('#mybutton').click(function()
{
$('#euro').toggleClass('hidden','shown'),
$('#pound').toggleClass('hidden','shown');
});
我不知该如何将其扩展到第三个id.感谢收到任何想法.
I'm at a loss to see how to extend this to the third id. Any ideas gratefully received.
推荐答案
我只想指出,您可能对toggleClass的工作方式感到困惑.第二个参数决不能是类似于类的字符串.相反,它是一个布尔值.我摆脱了"shown"类(默认情况下显示了所有内容),并为第二个参数使用了布尔值:
I just wanted to point out you may be confused on how toggleClass works. The second parameter is never a string like a class. Instead, it's a boolean. I've gotten rid of the "shown" class (things are shown by default) and used a boolean for the second argument:
i=0;
$('#mybutton').click(function(){
i++;
$('#euro').toggleClass('hidden', i%3!==0),
$('#pound').toggleClass('hidden',i%3!==1);
$('#dollar').toggleClass('hidden',i%3!==2);
});
所有这些操作是在自行车比赛(i%3 === 0)时删除隐藏的类,否则将其添加(隐藏这些元素).
All this does is remove the hidden class when the cycling matches (i%3===0) and add it (hide those elements) otherwise.
如果您 did 要在多个类之间切换,我相信第一个参数应该是用空格分隔的类列表.
If you did want to toggle between multiple classes, I believe the first argument should be a space separated list of classes.
http://api.jquery.com/toggleClass/
这篇关于两种状态的三向切换(JavaScript或jQuery)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!