Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
130 views
in Technique[技术] by (71.8m points)

Storing arbitrary info in HTML tags for JavaScript?

A very general question.

I am dynamically generating a form that is split into multiple levels of tabs using HTML / JavaScript.

I want to highlight some of the fields (those that have a value differing from a global template) with a star * symbol using CSS and background-image.

A JS field iterates through each field, compares its value, and sets a CSS class for it if necessary. So far, so good.

Now in addition, I want not only every changed field to be marked with a star, but also the tab it is in.

Because I love it simple, I would like to store the element ID of the tab as an attribute somewhere in each field's HTML tag (something like "parentTab"). The JS function then highlights the field and its "parentTab" element (and maybe that one's "parentTab" as well).

My first approach is to misuse the "title" attribute or somethiong to store parentTab in. Of course, that's dirty. However, if I just wildly add arbitrary attributes to the DIV or INPUT tag, it won't validate any more and I feel less than secure accessing these attributes - who knows how different browsers handle it, and will handle it in the future?

So my question is: Is there a valid, standards compliant way - an attribute of some sort - to store arbitrary data inside HTML tags, for further processing by JavaScript?

Of course, I could create a "parentTabs" JS array and be done with it. But storing it in the input itself would be so much more elegant.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

with the introduction of html5, you can use attributes that start with data-, and they'll still validate.

<input type="text" name="username" data-parentTab="tab1" value="non-default">

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...