声明变量jQuery

时间:2014-09-15 19:27:40

标签: javascript jquery variables var

if (window.location.href.indexOf("aaa") > -1)
{
    $("#wrap").css({display: 'block'});
    $("#nav").css({display: 'block'});
}
if (window.location.href.indexOf("bbb") > -1)
{
    $("#wrap").css({display: 'block'});
    $("#nav").css({display: 'block'});
}
if (window.location.href.indexOf("ccc") > -1)
{
    $("#wrap").css({display: 'block'});
    $("#nav").css({display: 'block'});
}
...

是否可以:

var url = ["aaa","bbb","ccc"......]

if (window.location.href.indexOf(url) > -1)
{
    $("#wrap").css({display: 'block'});
    $("#nav").css({display:'block'});
}

2 个答案:

答案 0 :(得分:0)

您可以使用for来循环遍历数组元素:

var url = ["aaa", "bbb", "ccc"]

for (var i = 0; i < url.length; i++)
{
    if (window.location.href.indexOf(url[i]) > -1)
    {
        $("#wrap").css({display: 'block'});
        $("#nav").css({display: 'block'});
        break;
    }
}

答案 1 :(得分:0)

不,那是不可能的,但您可以使用grep方法查看数组中的项目:

var url = ["aaa","bbb","ccc", ... ];
var href = window.location.href;

if ($.grep(url, function(u) { return href.indexOf(u) != -1; }).length) {
  $("#wrap,#nav").css({ display: 'block' });
}