【发布时间】:2013-08-16 02:32:50
【问题描述】:
我正在尝试在用户单击单词时创建不同的颜色状态
我的html
<a href='#' class='click' id='2'>
word
</a>
<a href='#' class='click' id='3'>
second word
</a>
我想根据id切换文字背景。
例如,当用户单击word -> 将背景颜色更改为黄色再次单击 -> 橙色并再次单击 -> 原始(白色和透明)。这是 2 个州。
第二个例子当用户点击second word -> 将背景颜色更改为黄色再次点击 -> 橙色,再次点击 -> 绿色并再次点击 -> 红色并再次点击 ->(白色和透明)这是 3 种状态
颜色状态基于 id 属性。
我的代码是这样的
$('.click').click(function(){
var states = $(this).attr('id');
var classname = $(this).attr('class');
switch (classname){
case 'click':
$(this).attr('class', 'yellow');
$(this).css('background-color', 'yellow');
break;
case 'yellow':
$(this).attr('class', 'orange');
$(this).css('background-color', 'orange');
break;
case 'orange':
$(this).attr('class', 'red');
$(this).css('background-color', 'red');
break;
case 'red':
$(this).attr('class', 'click');
$(this).css('background-color', 'white');
break;
//add more if I have too…..
}
})
我试图弄清楚如何根据id 切换颜色,而不是硬编码它。任何人都可以帮助我吗?非常感谢!
【问题讨论】:
标签: javascript jquery