开发者

Is there any attribute of <li> tags that I could use for storing server-side Id(s) of items(s)?

I want to store server-side Id(s) of items within an attribute defined on <li> tags, such that I could retrieve them within JS methods when there is a click event on them.

Is there any attribute that I could use to store this kind of data?

I tried putting server side ids of items into id attribute of <li> tags but it doesnt all开发者_Python百科ow ids starting with digits !


HTML5 introduces data- attributes which can be very useful in cases such as this one.

<li data-something="test">...</li>

Then, in JavaScript, you can fetch using:

elem.getAttribute('data-something');

or (not IE supported):

elem.dataset.something;

http://jsfiddle.net/9g33e/


generally, you should use data-* attributes..

<li data-myInformation="123">This is item 123</li>

These can be retrieved easily, and popular frameworks such as jQuery support easy access to these attributes with a element.data("myInformation") method.


If I've understood your problem correctly, then there shouldn't be a problem using the id attribute, unless of course you are already using that for another purpose.

The spec shows the valid attributes for li elements:

id, class, lang, dir, title, style, and a bunch of event handler attributes (onclick and the like).

In theory you could use pretty much any of those to store your data, but id would be my preferred choice. However, it's important to remember that id attribute values have to start with a letter (unless you're using the doctype mentioned below, but in that case it would be better to use the below method anyway).

As others have mentioned, if you are using a <!DOCTYPE html> doctype, then you can use the new data-* attributes which are intended for this exact use.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜