javascript 如何在 Backbone.js 中设置视图的 id?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13094306/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 17:48:34  来源:igfitidea点击:

How to set the id of a View in Backbone.js?

javascriptjquerymodel-view-controllerbackbone.js

提问by RobotEyes

In Backbone.js when I create a view I can initialise the 'class' attribute of it's element as shown below:

在 Backbone.js 中,当我创建一个视图时,我可以初始化它的元素的 'class' 属性,如下所示:

var newView = Backbone.View.extend({
    className: 'foo'
});

Is there a similar way to set the 'id' attribute in a similar way?

是否有类似的方法以类似的方式设置“id”属性?

回答by Jim

var newView = Backbone.View.extend({
    id: 'foo1',  // or
    tagName: 'foo2', // or ..
    className: 'foo3' // 
});

Hope that helps!

希望有帮助!

回答by John Munsch

There is an existing id property you can use. Here's a relevant portion from the docs:

您可以使用现有的 id 属性。这是文档中的相关部分:

elview.el All views have a DOM element at all times (the el property), whether they've already been inserted into the page or not. In this fashion, views can be rendered at any time, and inserted into the DOM all at once, in order to get high-performance UI rendering with as few reflows and repaints as possible. this.el is created from the view's tagName, className, id and attributes properties, if specified.If not, el is an empty div.

elview.el 所有视图始终都有一个 DOM 元素(el 属性),无论它们是否已经插入到页面中。以这种方式,视图可以随时渲染,并一次性插入到 DOM 中,以获得高性能的 UI 渲染,并尽可能减少回流和重绘。this.el 是从视图的 tagName、className、id 和 attributes 属性创建的,如果指定的话。如果没有,el 是一个空的 div。

Also, you can bind to an existing element that is already in the HTML if that works better for you.

此外,如果这对您更有效,您可以绑定到 HTML 中已有的现有元素。