-1

我觉得这里有太多重复的代码。我所做的只是对 URL 中的字符串进行基本的正则表达式匹配。如果找到匹配项,我会找到一个带有类(.index、.grid、.type)的 li 并添加活动类。这只是为了我的主要导航,试图让它变得更有活力。但是,我觉得有一种更有效的编码方式。任何帮助是极大的赞赏。

$( document ).ready(function() {
var myLocation = window.location;
var convertURL = new String(myLocation);
var index = /index/i;
var grid = /grid/i;
var type = /type/i;
var urlIndex = convertURL.match(index);
var urlGrid = convertURL.match(grid);
var urlType = convertURL.match(type);
if(urlIndex) {
$('.index').addClass('active'); 
}else if(urlGrid) {
$('.grid').addClass('active');
}else if(urlType) {
$('.type').addClass('active');
    }

});
4

2 回答 2

1
$(function(){
    ["index", "grid", "type"].forEach(function(term){
        if(new RegExp(term, "i").test(location.href)) 
            $("." + term).addClass("active"); 
    });
});
于 2014-05-26T00:37:19.237 回答
-1
$(document).ready(function () {

    // use single var per function, good for minimizing and other stuff
    var

    i,

    // new string literal, not String object
    convertURL = '' + window.location,

    // the array of strings keeps only the difference from the repetitive code
    classes = ['index', 'grid', 'type'],

    // using functions with proper arguments reduces repetitivness
    matches = function (regex) {
        return convertURL.match(new RegExp(regex, 'i'));
    }

    // var
    ;

    // always use += instead of ++ -> makes for clear intention
    for (i = 0; i < classes.length; i += 1) {
        if (matches(classes[i])) {
            // returning out of this function stops iteration
            return $('.' + classes[i]).addClass('active');
        }
    }

});
于 2014-05-26T00:38:05.877 回答