意见:在HTML中,可能的重复ID或非标准属性? [英] Opinion: in HTML, Possible Duplicate IDs or Non-Standard Attributes?

查看:166
本文介绍了意见:在HTML中,可能的重复ID或非标准属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎很常见的想让你的javascript知道一个特定的dom节点对应于数据库中的记录。

It seems pretty common to want to let your javascript know a particular dom node corresponds to a record in the database. So, how do you do it?

我已经看到的一种方法是使用类的类型和id的id:

One way I've seen that's pretty common is to use a class for the type and an id for the id:

<div class="thing" id="5">
<script> myThing = select(".thing#5") </script>

这有一个轻微的html标准问题,虽然 - 如果你有多种类型的记录该页面,您可能会最终重复ID。

There's a slight html standards issue with this though -- if you have more than one type of record on the page, you may end up duplicating IDs. But that doesn't do anything bad, does it?

另一种方法是使用数据属性:

An alternative is to use data attributes:

<div data-thing-id="5">
<script> myThing = select("[data-thing-id=5]") </script>

这解决了重复ID问题,但这意味着你必须处理属性而不是ID ,这有时更加困难。

This gets around the duplicate IDs problem, but it does mean you have to deal with attributes instead of IDs, which is sometimes more difficult. What do you guys think?

推荐答案

请注意,ID不能以数字开头,因此:

Note that an ID cannot start with a digit, so:

<div class="thing" id="5">

是无效的HTML。请参见什么是id属性的有效值? HTML

is invalid HTML. See What are valid values for the id attribute in HTML?

在这种情况下,我会使用 thing5 thing.5

In your case, I would use ID's like thing5 or thing.5.

这篇关于意见:在HTML中,可能的重复ID或非标准属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆