简体   繁体   中英

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/

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.

Addition: You could pass the currentItem as a parameter instead of using global variable.

Here is the working demo.

I think you're complicating things too much, can't you just do this?

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:

$('a.color').click(function(){
    $('body').css('background-color', $(this).text());
});

Demo: 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:

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

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. just use parseInt function.

Maybe you have to give the parameter 'currentItem' with the function call.

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

http://jsfiddle.net/cF74Y/34/

use parseInt to compare with case.With this its unable to compare.See fiddle. http://jsfiddle.net/cF74Y/43/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM