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

标签 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()});

}
});

但是我不知道如何让它变得更好,我正在考虑让它成为一个循环,但我不知道 -.-.. 请帮忙!

最佳答案

我将创建一个有效 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()
    });

关于Javascript,我可以将其更改为循环吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21033255/

相关文章:

jquery 不引人注目

javascript - 在 JS/C#/MVC4 中将 json 转换为 csv 文件并填充 AccessDB

javascript - 如何将数组中的值从 asp.net 更改为 javascript

javascript - 良好的 Javascript 模板引擎,可与 JSON 一起使用

javascript - 在 html 中清除链接的 css 属性

javascript - Slick 轮播在调整大小期间隐藏最后一张幻灯片,slickGoTo 无法按预期工作

javascript - 在 typescript 中始终使用 .tsx 而不是 .ts 有什么缺点吗?

Javascript:如何在 HTTP GET 中传递当前用户凭据以进行基本身份验证

jquery - 拖放 - 检查项目是否放置在正确的位置

javascript - 使用 JQuery 预填充选择字段的下拉选项验证