2011-02-28 76 views
2

I'm doing this mainly to store data inside tags as I echo it out of php, and then using jQuery to $(..).attr('my_att') to retrieve it.不使用自定义标签属性如<a my_att='...'>

It hasn't caused any problems so far, but are there good reasons (other than it's not valid) why we shouldn't do this?

+0

你知道[数据属性](http://www.w3.org/TR/html5/elements.html#embedding-custom-non-visible-data-with-the-data-attributes)吗? – 2011-02-28 15:54:56

+0

“......但是有没有很好的理由(除了这是无效的),为什么我们不应该这样做?” ...这就是微软的Internet Explorer开发人员在几年前说过的......:D – vtortola 2011-02-28 15:56:25

+0

[Custom attributes - Yay or nay?]的可能重复(http://stackoverflow.com/questions/992115/custom-attributes- yay-or-nay) – 2011-02-28 15:58:43

回答

3

Because you can use valid custom attributes instead:

<div data-customer-id="3" class="customer"> [...] </div> 

If you prefix your attributes with data- they are valid HTML. The reason for not just writing your own attributes is that they can wind up inheriting meaning in the future. Obviously this is unlikely for some cases (like "customer-name"), but using the prefix is safter.

Another added benefit is that you are very clear about your intentions; another developer isn't going to come by and think you meant to write kind="text" rather than type="text" when you were trying to mark the model associated with a particular input field.

3

I prefer to do that sort of thing as HTML5 data attributes有什么好的理由。

然后,您可以使用jQuery.data()来获取属性,如果您在浏览器中原生不支持数据属性。

例如:

<a href="#" id="MyLink" data-address="1600 Pennsylvania Ave, Washington, DC"> 
    My Address 
</a> 

然后,我可以做$('#MyLink').data('address')得到值回。

0

我看主要有两个原因,以避免使用自定义属性:

1°如果浏览器确实是严格对HTML标准,他可以简单地拒绝出示不符合的DTD或者更糟页面,试图显示你的页面崩溃。

2°浏览器可以选择从元素中去除未知属性。

当然,实际上,没有浏览器能够做这些事情,但谁可以说新的实现将来会做什么?

标准的制定是有原因的,遵循它们总是一个好主意。特别是当HTML5让您轻松创建自定义属性时。