2014-01-28 56 views
0

我不能完全找出解决这个问题的最佳方法。我有一个条件,根据是否存在选择器来设置Cookie 。代码中还有其他地方,如果 选择符存在,我可以做类似的事情。如果选择器存在,我可以将“nba”或“nba-”(注意破折号)添加到页面上的各种属性 。我试图删除尽可能多的代码,因为有大约五个其他地方 我有类似的地方,我添加其他属性。我也觉得自己有一个更好的方式 处理这个不必此写一吨的时候:jQuery - 如果选择器存在,添加属性和前缀值

if($(".userLocation").length > 0){ 

我敲我的脑袋上如何凝聚这一点,但可能不知道这一点。请包括代码示例 我学到最好的方式。

if($(".userLocation").length > 0){ 
     var user_cookie = { 
     name: 'nba-user-profile', 
     options: { 
      path: '/', 
      expires: 365 
     } 
     }; 
    } else { 
     var user_cookie = { 
     name: 'user-profile', 
     options: { 
      path: '/', 
      expires: 365 
     } 
     }; 
    } 

if($(".userLocation").length > 0){ 
$('header').attr("href","#nba-city"); 
$('header').attr("href","#nba-state"); 
} else { 
$('header').attr("href","#city"); 
$('header').attr("href","#state"); 
} 

if($(".userLocation").length > 0){ 
$('header').attr("title","#nbacity"); 
$('header').attr("title","#nbastate"); 
} else { 
$('header').attr("title","#city"); 
$('header').attr("title","#state"); 
} 
+0

我没有得到该问题。如果你想避免重复if(condition)创建一个布尔函数,或者将布尔值存储在一个变量中,那么你在使用这些函数时如果使用了相同的函数 – Alessio

+0

为什么不写这个条件一次并更改所有的属性在一个块中。 – Krishna

回答

2

可能是效率不高,但你可以尝试像

function existThenDo(selector, successCallBack, failCallback){ 
    if($(selector).length){ 
     successCallBack(); 
    } else { 
     failCallback(); 
    } 
} 

使用的东西

existThenDo(".userLocation", function(){ 
    $('header').attr("title","#nbacity"); 
    $('header').attr("title","#nbastate"); 
}, function(){ 
    $('header').attr("title","#city"); 
    $('header').attr("title","#state"); 
}); 
+0

对不起@Satpal在这里困惑,因为如果我想用nba而不是nba作为前缀呢? –

+0

@DelmonYoung,你为什么困惑?当您在多个位置执行多个操作时。我只是在一个函数中包装你的if。不,你可以在__successCallBack__和__failCallback__中做任何你想做的事情 – Satpal

1

如何这样的事情。创建一个前缀变量。如果选择器存在,请将其设置为您的前缀值,否则将其保留为空。然后,只需追加任何有:

var prefix = ''; 


if($(".userLocation").length > 0) 
    prefix = 'nba-'; 

var user_cookie = { 
    name: prefix + 'user-profile', 
    options: { 
     path: '/', 
     expires: 365 
    } 
}; 

$('header').attr("href","#" + prefix + "city"); 
$('header').attr("href","#" + prefix + "state"); 

这减少了一半必要的代码,因为你不必再重复同样的事情,如果/ else块。