【问题标题】:How to the same page specific code for multiple pages using javascript routes?如何使用 javascript 路由为多个页面使用相同的页面特定代码?
【发布时间】:2013-09-12 07:07:59
【问题描述】:

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

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();

【问题讨论】:

  • '003.html' 后面缺少一个 ] 来关闭数组。这是您的真实代码还是您在此处传输时犯了这个错误?在 route.add 方法中,您必须检查参数 url 是否为数组并相应地填充 this._routes。
  • 这是样板代码。缺少的括号只是一个错字。我真的很感谢你的帮助。你的代码当然有效!!!

标签: javascript jquery routes


【解决方案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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-20
    • 1970-01-01
    • 1970-01-01
    • 2011-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多