Javascript 如何为主干路由构造动态URL?

Javascript 如何为主干路由构造动态URL?,javascript,jquery,html,backbone.js,url-routing,Javascript,Jquery,Html,Backbone.js,Url Routing,我这里的路线很复杂。为子视图构造URL以导航到不同的父视图 domain.com/categories/1/details domain.com/categories/1/price domain.com/categories/1/owner domain.com/categories/2/details domain.com/categories/2/price domain.com/categories/2/owner 我需要构建详细信息,价格和所有者视图的网址 <

我这里的路线很复杂。为子视图构造URL以导航到不同的父视图

domain.com/categories/1/details  
domain.com/categories/1/price  
domain.com/categories/1/owner

domain.com/categories/2/details  
domain.com/categories/2/price  
domain.com/categories/2/owner
我需要构建详细信息,价格和所有者视图的网址

<a href="#/categories/id/price">Price</a>
<a href="#/categories/id/details">details</a>
<a href="#/categories/id/owner">owner</a>

需要动态替换id

如何构建它们?

您可以尝试以下方法:

var myRouter = Backbone.Router.extend({
          routes : {}
    });
    myRouter.on('route:categories/:id/details' function() {

    });

    myRouter.on('route:categories/:id/price' function() {

    });

    myRouter.on('route:categories/:id/owner' function() {

    });

在视图的模板中,您将拥有:

<script type="text/template" id="my-template">
    <a href="#/categories/<%= id %>/price">Price</a>
    <a href="#/categories/<%= id %>/details">details</a>
    <a href="#/categories/<%= id %>/owner">owner</a>
</script>

然后在视图的render方法中,只需传入id变量

<script type="text/javascript">
    var userId = 42;

    var MyView = Backbone.View.extend({
        initialize: function(){
            this.render();
        },
        render: function(){
            // Compile the template using underscore
            var template = _.template( $("#my-template").html(), {id: userId});

            // Load the compiled HTML into the Backbone "el"
            this.$el.html( template );
        }
    });
</script>

var-userId=42;
var MyView=Backbone.View.extend({
初始化:函数(){
这个。render();
},
render:function(){
//使用下划线编译模板
var template=35;.template($(“#我的模板”).html(),{id:userId});
//将编译后的HTML加载到主干“el”中
这个.$el.html(模板);
}
});

这里有一点关于这个主题的更多信息,可能会有所帮助:

您是否阅读过文档?是的。但是我需要导航到常见视图“categories/:id/:section”我可以路由它,但问题是href=“categories/?/section”。我不想重新初始化整个视图。所以在视图首次初始化时您没有这些值?如果是这样的话,您可以向视图中添加一个函数,该函数将int插入DOM,获取a元素,然后修改SRC(使用jQuery)。