gpt4 book ai didi

jquery - 定义 "custom"HTML 标签是不好的做法吗

转载 作者:搜寻专家 更新时间:2023-10-31 22:57:50 26 4
gpt4 key购买 nike

我在我的代码中使用自定义 HTML 标记 ( <include> )。这是不好的做法吗?如果是的话,应该用什么来代替。

在我看来,它通过在标记名称中具有含义而不是 <div class="include"> 来增加代码的可读性.

最佳答案

自定义 HTML 标签被误解,实际上应该被视为最佳实践

浏览器将毫无问题地下载和解析具有自定义或未知 标签的标记。浏览器还会使用您提供的 CSS 规则来设置它们的样式。这是一个例子:

HTML

<my-alert status="success">Hello custom tags!</my-alert>

CSS

my-alert[status="success"] { 
color: white;
background-color: green;
}

前端世界为类疯狂(部分原因是旧浏览器不能很好地处理未知标签*),所以上面通常是这样完成的:

HTML

<div class="alert alert-success">Hello custom tags!</div>

CSS

.alert.alert-success { 
color: white;
background-color: green;
}

两者的工作方式完全相同,但自定义标签设计与自定义元素规范保持一致,使用熟悉的 HTML 结构(标签、属性、嵌套),并准备这个小的静态警报以演变成真正的自定义元素或 Web 组件以基于标准的向后兼容的方式。我认为自定义标签代码看起来也比带有一堆类的非语义标签好得多。

这里有一个更深入的解释(完全公开:我写的):

https://dev.to/jfbrennan/custom-html-tags-4788

*旧的 HTML 2.0 规范对于未知标签的容错性不是很好,但值得庆幸的是,HTML 4.01 改变了这一点:

to facilitate experimentation and interoperability between implementations of various versions of HTML, we recommend the following behavior:

If a user agent encounters an element it does not recognize, it should try to render the element's content.If a user agent encounters an attribute it does not recognize, it should ignore the entire attribute specification (i.e., the attribute and its value).If a user agent encounters an attribute value it doesn't recognize, it should use the default attribute value.If it encounters an undeclared entity, the entity should be treated as character data.

供引用:https://www.w3.org/TR/html401/appendix/notes.html#notes-invalid-docs

关于jquery - 定义 "custom"HTML 标签是不好的做法吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37622348/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com