开发者

What are some good reasons for not using custom tag attributes such <a my_att='...'>

开发者 https://www.devze.com 2023-02-14 09:56 出处:网络
I\'m doing this mainly to store data inside tags as I echo it out of php, and then us开发者_如何学Cing jQuery to $(..).attr(\'my_att\') to retrieve it.

I'm doing this mainly to store data inside tags as I echo it out of php, and then us开发者_如何学Cing jQuery to $(..).attr('my_att') to retrieve it.

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?


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.


I prefer to do that sort of thing as HTML5 data attributes.

Then you can use jQuery.data() to get at the attributes if you're in a browser that doesn't support data attributes natively.

For example:

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

Then I can do $('#MyLink').data('address') to get the value back.


I see mainly two reasons to avoid using custom attributes :

1° If the browser is really strict about the HTML standard, he can simply refuse to show a page which don't comply to the DTD or worse, crash trying to display your page.

2° The browser can choose to strip unknown attribute from the element.

Sure, actually, no browser do either of these things, but who can say what new implementations will do in the future ?

Standards are developed for a reason, and it's always a good idea to follow them. Especially when HTML5 let you create custom attributes so easily.

0

精彩评论

暂无评论...
验证码 换一张
取 消