2011-02-28 45 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讓您輕鬆創建自定義屬性時。