Javascript,我可以将其更改为循环吗?

时间:2014-01-09 23:19:38

标签: javascript jquery

我正在制作导航栏并让它正常工作。但我想改变我的写作。有重复的代码如下所示:

$("nav span").mouseover(function(){
var currentColor = $("#" +$(this).attr("data-loc")).css("backgroundColor");
var currentPos = $(this).position().left;

if ($(this).attr("data-loc") === "home"){
    $("#hoverstyle").animate({"left":currentPos},150);
    $("#hoverstyle").css("backgroundColor",currentColor);
    $("#hoverstyle").css({width:$(this).width()});

}
else if($(this).attr("data-loc") === "writer"){
    $("#hoverstyle").animate({"left":currentPos},150);
    $("#hoverstyle").css("backgroundColor",currentColor);
    $("#hoverstyle").css({width:$(this).width()});
}
else if($(this).attr("data-loc") === "historian"){
    $("#hoverstyle").animate({"left":currentPos},150);
    $("#hoverstyle").css("backgroundColor",currentColor);
    $("#hoverstyle").css({width:$(this).width()});

}
else if($(this).attr("data-loc") === "teacher"){
    $("#hoverstyle").animate({"left":currentPos},150);
    $("#hoverstyle").css("backgroundColor",currentColor);
    $("#hoverstyle").css({width:$(this).width()});

}
else if($(this).attr("data-loc") === "fencing"){
    $("#hoverstyle").animate({"left":currentPos},150);
    $("#hoverstyle").css("backgroundColor",currentColor);
    $("#hoverstyle").css({width:$(this).width()});

}
});

但是我无法弄清楚如何让它变得更好,我想把它变成一个循环,但我想不出来 - .- ..请帮忙!

2 个答案:

答案 0 :(得分:8)

我会创建一个有效的loc值数组,然后查看该元素是否在该数组中有值。

var locs = ['home', 'writer', 'historian', 'teacher', 'fencing'];

var thisLoc = $(this).attr('data-loc');
if (locs.indexOf(thisLoc) > -1) {
  //do stuff
}

Array indexOf方法返回项目索引(如果在数组中找到它)。否则返回-1。因此,如果您更多-1,则您知道data-loc值在您的数组中,您可以采取行动。


您还可以通过重用$('#hoverstyle')对象来清理您的jQuery操作,这称为链接。 jQuery的方法通常会返回jQuery对象,这样您就可以链接调用而无需再次查找对象。并且您可以将css()调用与传入对象的一个​​调用与两个属性组合。

$("#hoverstyle")
    .animate({"left":currentPos},150)
    .css({
        backgroundColor: currentColor,
        width:$(this).width()
    });

答案 1 :(得分:3)

切换声明?

switch ($(this).attr("data-loc"))
{
   case "home":
   case "writer":
   case "historian": 
   case "teacher":
   case "fencing":
       $("#hoverstyle").animate({"left":currentPos},150);
       $("#hoverstyle").css("backgroundColor",currentColor);
       $("#hoverstyle").css({width:$(this).width()});
       break;
   default: 
       break;
}
相关问题