0

Is there a better way of writing this? Seems like the if statements could be combined somehow.

Here is the HTML

<header class="gray_bg" id="main_header">

I wrote this code to change the class name of this header tag. It works just fine, but I feel like it could be shorter. Any help would be great as I am still learning JS/jQuery. Thanks!

$("nav#main_nav li a").on('click', function(){
    var link = $("nav#main_nav li a").index(this);
    var banner = $("header#main_header");

    if (link === 0) {
        banner.attr('class', "gray_bg");
    }

    if (link === 1) {
        banner.attr('class', "orange_bg");
    }

    if (link === 2) {
        banner.attr('class', "green_bg");
    }

    if (link === 3) {
        banner.attr('class', "purple_bg");
    }
});
4

2 回答 2

4
$("nav#main_nav li a").on('click', function(){
    var link = $("nav#main_nav li a").index(this);
    var colors = ["gray_bg", "orange_bg", "green_bg", "purple_bg"];

    $("header#main_header").attr('class', colors[link]);
});
于 2013-07-18T02:54:25.797 回答
1

只需将您的类放入数组中,然后使用您获得的索引从中读取

var classes = ["gray_bg" ,"orange_bg","green_bg" ,"purple_bg"];
$("nav#main_nav li a").on('click', function(){
    var link = $("nav#main_nav li a").index(this);
    var banner = $("header#main_header");


    banner.attr('class', classes[link]);

});
于 2013-07-18T02:55:23.240 回答