在 html/javascript 中这样用 是否 合法? 如果不合法有没有通用方便的解决方案呢?

2011-08-28 12:39:28 +08:00
 darasion
举例,列表中的
<ul>
<li><a article_id="1" class="xxx">1234567</a></li>
<li><a article_id="2" class="xxx">1234567</a></li>
<li><a article_id="4" class="xxx">1234567</a></li>
<li><a article_id="55" class="xxx">1234567</a></li>
<li><a article_id="6" class="xxx">1234567</a></li>
</ul>


这样做的目的是想一下子将所有条目绑定事件,并引用id:
$('.xxx').click(function(){
var article_id=$(this).attr('article_id');
//....利用 article_id 做一些事..
});


像例子里 article_id 这种不存在的 html 属性是否合法呢?
如果不合法,那么有没有其他的办法能够达到上述效果呢?
3730 次点击
所在节点    问与答
16 条回复
cynial
2011-08-28 12:45:52 +08:00
为什么不直接用id属性呢
Hyperion
2011-08-28 12:52:25 +08:00
加 data-article_id , HTML5里可以这么干...
http://www.w3.org/TR/html5/elements.html#embedding-custom-non-visible-data-with-the-data-attributes

xhtml, 我估计会通不过严格检查吧...
raptium
2011-08-28 12:53:06 +08:00
raptium
2011-08-28 12:53:31 +08:00
啊呀 发慢了…… 还不能删除 ~~
Hyperion
2011-08-28 12:53:53 +08:00
@raptium 同步了... /握手
chloerei
2011-08-28 12:55:02 +08:00
xhtml已死,不用考虑
不考虑老浏览器的话用data-
orzzzzz
2011-08-28 13:01:48 +08:00
自定义属性是可以用的.....
chuck911
2011-08-28 13:09:42 +08:00
1. XHTML, with a specific namespace
http://www.bennadel.com/blog/1453-Using-jQuery-With-Custom-XHTML-Attributes-And-Namespaces-To-Store-Data.htm
<html ... xmlns:xyz="http://www.yourdomain.com">
... <a xyz:article_id="11">...

2. $.data()
The jQuery.data() method allows us to attach data of any type to DOM elements

3. Custom DTD
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
[
<!ATTLIST a article_id CDATA #IMPLIED>
]>

4. html5 data-*
<a data-article_id="55" class="xxx">1234567</a>
darasion
2011-08-28 13:12:18 +08:00
hi all,

当然要考虑通用了. html5虽然很好, 但是用户不用它也白搭呀.
Hyperion
2011-08-28 13:13:20 +08:00
@chuck911 自定义命名空间, 自定义DTD么...
darasion
2011-08-28 13:13:51 +08:00
@chuck911 多谢这个..
chuck911
2011-08-28 13:15:12 +08:00
我觉得XHTML自定义namespace的方案比较方便且通用
jQuery.data()在你这个情况可能不方便了,article_id是服务端生成的吧
loading
2011-08-28 13:15:23 +08:00
建议通过 href 来操作。
<a href="#mark1" >xxxx</a>
<a href="#mark2" >xxxx</a>

或者通过 class,class="xxx mark1 mark2 ..."
darasion
2011-08-28 13:25:58 +08:00
@loading 谢谢, 这样做的好处是?
loading
2011-08-28 14:00:24 +08:00
@darasion 我不知道你用来做什么,如果只是要个标记,开关什么的,这样较为简单。
如果是较多的数据,直接ajax就好了。json很方便的。放那么多不是给用户看的控制数据到html干什么
chloerei
2011-08-28 15:05:59 +08:00
http://caniuse.com/#feat=dataset

Note: All browsers can already use data-* attributes and access them using getAttribute. "Supported" refers to accessing the values using the dataset property.

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/17424

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX