[英]JavaScript switch for changing background colour with css()
I have a very simple function which should change the page background colour based on specific links being clicked, but I can't figure out why it's not working. 我有一个非常简单的功能,该功能应该根据所单击的特定链接来更改页面背景颜色,但是我不知道为什么它不起作用。
Here is a demo of what I have so far: http://jsfiddle.net/cF74Y/ 这是到目前为止的演示: http : //jsfiddle.net/cF74Y/
It seems like it must be such a trivial mistake, but I can't see it. 看来这肯定是一个微不足道的错误,但我看不到它。 Any help would be greatly appreciated.
任何帮助将不胜感激。
You are compare string with number, change switch (currentItem)
to switch (+currentItem)
will make your demo work. 您将字符串与数字进行比较,将
switch (currentItem)
更改为switch (+currentItem)
将使您的演示工作正常。
Addition: You could pass the currentItem
as a parameter instead of using global variable. 另外:您可以将
currentItem
作为参数传递,而不是使用全局变量。
I think you're complicating things too much, can't you just do this? 我认为您使事情变得过于复杂,难道您不可以这样做吗?
html: 的HTML:
<ul id="nav">
<li><a class="color" href="#">red</a></li>
<li><a class="color" href="#">green</a></li>
<li><a class="color" href="#">blue</a></li>
<li><a class="color" href="#">yellow</a></li>
</ul>
jQuery: jQuery的:
$('a.color').click(function(){
$('body').css('background-color', $(this).text());
});
Demo: http://jsfiddle.net/elclanrs/8yev9/ 演示: http : //jsfiddle.net/elclanrs/8yev9/
Edit: And if you need to assign a color by index use an array, I don't think you need that ugly switch
statement, seems pretty useless to me, all that code can be reduced to just this: 编辑:并且,如果您需要使用数组通过索引分配颜色,我认为您不需要那丑陋的
switch
语句,对我来说似乎毫无用处,所有这些代码都可以简化为:
var colors = ['red', 'blue', 'green', 'yellow'];
$('a.color').click(function(){
$('body').css('background-color', colors[$(this).parent().index()]);
});
Demo: http://jsfiddle.net/elclanrs/8yev9/1 演示: http : //jsfiddle.net/elclanrs/8yev9/1
try this: 尝试这个:
var index = parseInt($(this).attr('id'),10);
then it will work. 那么它将起作用。
Reason: the return type of .attr() function is a string and it make true case 1 always. 原因:.attr()函数的返回类型为字符串,并且始终为true情况1。 just use parseInt function.
只需使用parseInt函数。
Maybe you have to give the parameter 'currentItem' with the function call. 也许您必须在函数调用中给参数“ currentItem”。
changeBg(currentItem); // call
And your function will look like this: 您的函数将如下所示:
function changeBg(currentItem) {
var bg = 'null';
switch (currentItem) {
case 1 :
bg = '#6A6A6A';
[..]
here is a working copy 这是工作副本
use parseInt
to compare with case.With this its unable to compare.See fiddle. 使用
parseInt
与大小写进行比较,因此无法进行比较。 http://jsfiddle.net/cF74Y/43/ http://jsfiddle.net/cF74Y/43/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.