html - 仅使用属性来标记 html 元素是一种好习惯吗?

标签 html design-patterns

我对使用 Javascript 编写 HTML 的良好做法存有疑问。

我想出了一个想法(可能不是第一个,但找不到关于它的明确引用)将一些元素标记为候选元素,以便在数据可用时(在一些用户交互之后)加载一些数据。让我举例说明:

假设我有一个返回以下内容的请求:

GET    /animals/dog

{
  name: "Gutemberg",
  race: "doberman",
  age: "2y"
}

我编写的代码将响应中的字段绑定(bind)到作为加载此类值的候选元素。 例如:对于上面的请求,我可以使用以下标签:

<input name="dog-name-field" data-load-dog-name type="text"/>
<input name="dog-age-hid" data-load-dog-age type="hidden"/>

每个标签都会收到属性值,因为它被标记为这样做的候选者 - dog-name-field 将在所有内容执行时具有“Gutemberg”值。每次重新加载请求时都会发生这种情况。现在,我只获取我搜索过的数据类型(“dog”),将其与属性“name/age”连接以形成属性 data-load-type-property 并为具有该属性的每个人设置一个值。

我觉得属性不应该像那样使用,但我不知道这样做有什么真正的缺点。由于这种方法没有明确的名称,我找不到它,因此我需要一些指导。

这种技术有名称吗?这是一种不好的做法吗?如果是,为什么?

附言: 为了遵守 SO 良好做法,我希望答案以引用为指导,而不是尽可能仅基于意见。如果没有提供引用,请让我们有一个可靠的、描述清楚的例子。

最佳答案

I have a feeling that attributes are not meant to be used just like that

让我们看看自定义数据属性的用途:

Custom data attributes are intended to store custom data private to the page or application, for which there are no more appropriate attributes or elements. These attributes are not intended for use by software that is independent of the site that uses the attributes.

(来自 w3.org)

因此,在您的情况下使用 data-attributes 是否“合适”取决于您的需求:如果 DOM API 没有提供更好的属性来做到这一点,那么它就是合适的。

如果您的需要只是选择一些元素来更改 textContent 那么您有两个更合适/更简单的选项:

1) 如果您的元素在文档中是唯一的,则使用 id 属性

The id global attribute defines a unique identifier (ID) which must be unique in the whole document. Its purpose is to identify the element when linking (using a fragment identifier), scripting, or styling (with CSS).

(来自 MDN 上的 id)

2) 如果您的元素将在文档中的多个实例中使用,则使用 class 属性

The class global attribute is a space-separated list of the classes of the element. Classes allows CSS and Javascript to select and access specific elements via the class selectors or functions like the DOM method document.getElementsByClassName.

(来自 MDN 上的 class)

正如@Supr 在他的回答中所说,您正在做的是一个非常简单的 data-binding 实现。 . 数据绑定(bind) 可能比您目前正在做的复杂得多;例如你可能想要:

  • 让您的 UI 与代表您的业务模型的 Javascript 对象保持同步,而不是直接注入(inject)来自 Ajax 调用的数据,

  • 更新其他属性(值、样式),而不仅仅是 innerHTML 或 textContent,

  • 更新您的业务模型以响应 UI 上的变化 (two way data binding)

要实现所有这些功能,简单的 idclass 选择器是不够的,这就是为什么实现数据绑定(bind)的框架,如 KnockoutJS 或 AngularJS,使用更灵活的 data-* 属性代替(AngularJS 实际上使用它自己的 ng-* 属性,但允许使用替代的 data-ng-* 使用 HTML 验证工具的语法)。

数据属性允许描述更复杂的绑定(bind):

<input data-bind="visible: editing, value: name, hasFocus: editing" />

检查 KnockoutJS documentation上面代码的含义,与本例无关,想象一下用classid来描述,会不会很方便。

长话短说

如果您不打算实现更复杂的功能,您可能希望使用 classid

关于html - 仅使用属性来标记 html 元素是一种好习惯吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33608275/

相关文章:

c++ - 重构单例/全局以使用依赖注入(inject)进行单元测试

java - GWT TextArea - 调整大小处理程序

javascript - 创建一个纵横比为 1 的 div :1 knowing only its height in percentage

html - 将厘米转换为像素,转换公式?

jquery - 在 MVC 中提供用户通知/确认的推荐方法是什么?

java - 命令模式基础知识

html - 在多张图像上添加删除按钮

html - 在鼠标悬停时显示表格条目的替代文本

python - 如何在 Python 中创建一系列文本菜单

javascript - HTML中 "template"标签、 "content"标签和自定义元素标签的区别