0

我想知道如何使用路由为多个页面执行相同的代码?这是我正在使用的示例:

var route = {
_routes: {}, // The routes will be stored here
add: function(url, action) {
    this._routes[url] = action;
},
run: function() {
    jQuery.each(this._routes, function(pattern) {
        if (location.href.match(pattern)) {
            // "this" points to the function to be executed
            this();
        }
    });
}
}

route.add(['002.html','003.html', function() {//This is not working it only work with one string
alert('Hello there!');
});
route.add('products.html','services.html', function() {//This is not working it only work with one string
alert("this won't be executed :(");
});
route.run();
4

1 回答 1

1

我更改为方法route.add,因此它也接受一个数组作为 url 参数。

var route = {
_routes: {}, // The routes will be stored here
add: function(url, action) {
    if( typeof url === 'string' ) { // if url isn't an array, convert it to an array
        url = [url];
    }
    for (var i=0; i<url.length; i++) { // loop over the array elements
        this._routes[url[i]] = action;
    }

},
run: function() {
    jQuery.each(this._routes, function(pattern) {
        if (location.href.match(pattern)) {
            // "this" points to the function to be executed
            this();
        }
    });
}
}

// array as url parameter
route.add(['002.html','003.html'], function() {
    alert('Hello there!');
});
// array as url parameter
route.add(['products.html','services.html'], function() {
    alert("this will be executed :)");
});
// string as url parameter
route.add('singlepage.html', function() {
    alert("this will be executed, too :)");
});
// log the generated variable route._routes
console.log(route._routes)
route.run();
于 2013-09-08T18:58:22.050 回答