javascript Backbone 视图中 tagName、id 和 className 属性的用途是什么?虽然我们可以使用 el 访问 dom 元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16172671/
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-27 03:34:22  来源:igfitidea点击:

What is use of tagName, id, and className properties in Backbone View? While we can access dom element with el

javascriptmodel-view-controllerbackbone.js

提问by ali asad

Why do the properties tagName, idand classNameexist in a Backbone View?

为什么属性tagName,idclassName存在于主干视图中?

回答by Loamhoof

Those properties are used if your view has to create its own element, that is, if it doesn't have a elattribute when instantiated (various reasons, I can go further in the matter). So you'll have a new element with the id id, classes classNameand attributes attributes.

如果您的视图必须创建自己的元素,也就是说,如果它el在实例化时没有属性(各种原因,我可以在这件事上更进一步),则会使用这些属性。因此,您将拥有一个带有 id id、 classesclassName和 attributes的新元素attributes

You can find the relevant piece of code here. This _ensureElementmethod is used in the view's constructor.

您可以在此处找到相关的代码段。此_ensureElement方法用于视图的构造函数中。

回答by sachinjain024

All Backbone views have an el property Read doc here. If you do not pass an el while instantiating a view, it will create an empty DIVand use it.

所有 Backbone 视图都有一个 el 属性Read doc here。如果在实例化视图时没有传递 el,它将创建一个空的DIV并使用它。

  • Now, just say you do not want to use DIVas the container to render your view. You want it to be a ULinstead. Just specify the tagNameproperty for your view and it will be used instead.

  • If you want to add some css classes to your container, use className.

  • If you want to add some attributes to it (For example you want to add data-*attributes to your el) use the attributesproperty of Backbone view.

  • 现在,只是说您不想DIV用作容器来呈现您的视图。你希望它是一个UL。只需tagName为您的视图指定属性,它将被使用。

  • 如果您想向容器中添加一些 css 类,请使用className.

  • 如果你想给它添加一些属性(例如你想data-*给你的 el添加属性),使用attributesBackbone 视图的属性。