What do other people think of using “custom” attributes to make things easier (in jQuery)

。_饼干妹妹 提交于 2019-12-06 09:53:37

If you're going to use custom attributes, I'd say use data- attributes, like this:

<li class="catalogueItem"><a data-pName='" & Product.Name & "' data-pID='" & Product.ID & "'>" & Product.Name & "</a></li>

In HTML5 data- prefixed attributes are for exactly this purpose...but won't cause any issues on an HTML4 document (though they are technically invalid). For now you access them like this:

$("li.catalogueItem").click(function() {
  $(this).html($(this).find("a").attr("data-pID"));
});

In the upcoming jQuery 1.5, .data() will look for them as a fallback as well, like this:

$("li.catalogueItem").click(function() {
  $(this).html($(this).find("a").data("pID"));
});

All modern browsers will not complain about this use of invalid HTML. That said, it still always bothers me. It's very common to see the use of the rel attribute to store data in the HTML. I also often tack on the id of something to the id attribute: <a id="product-384">My Product</a>

Once you're in the realm of JavaScript/jQuery, it's best to use jQuery's data() method. See http://docs.jquery.com/Data

As Cory Gagliardi wrote it's better to use jQuery.data (http://docs.jquery.com/Data) to store and read data in any HTML node.

Using jQuery.data method will add you some extra code (see work). The main idea is that you can store JavaScript Object in a HTML using a key.

Example:

$('li.catalogueItem item-0').data('item', {id:0, name:'My Item', desc:'...'});

For your actual .NET code you will be pushed to write this previous example for each item. Using a loop will do the job.

xmarcos

As Nick explains, it's and upcoming feature of jQuery and you should stick with that, since it'll be valid HTML5 code as well.

But i understand your are asking for personal experience, rather than technical justification.

So in my experience, use them as much as you need them.

HTML has been broken since the first day, it's missing a lot o useful features, but the good news are that you can workaround most of them without breaking functionality.

I have this rule, if you are building and application, not a public site (will be used by a wide and unknown audience), and you can have a controlled environment (read you can tell the app user what browser they should use), do whatever you have to do to make your app better, and that is better for the customer and better for you to develop/maintain/update.

Specs always change, and they always introduce features already in use ;)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!