admin管理员组文章数量:1334149
All too often I find myself storing object data in hidden dom elements. I was curious if there was a way to attach this data to the dom node itself. When I try to create attributes 'on the fly', it doesn't seem to work. It would be much easier to access the property with this.something instead of accessing the html contained in a child. I feel like I should know how to do this, but I don't. Thanks.
All too often I find myself storing object data in hidden dom elements. I was curious if there was a way to attach this data to the dom node itself. When I try to create attributes 'on the fly', it doesn't seem to work. It would be much easier to access the property with this.something instead of accessing the html contained in a child. I feel like I should know how to do this, but I don't. Thanks.
Share Improve this question asked Feb 4, 2011 at 0:02 Brandon FrohbieterBrandon Frohbieter 18.1k3 gold badges41 silver badges62 bronze badges 3-
As already mentioned, jQuery.data is probably what you are looking for. That said, look into the html5 specs and the
data-
attributes, which are pretty awesome, and something that you will see used already on many sites, since they don't break in non html5 browsers :) – Martin Jespersen Commented Feb 4, 2011 at 0:08 - Not sure why adding attributes 'on the fly' isn't working for you. Have a look at this example to see how to make it work (webdevout/test?01o) – nybbler Commented Feb 4, 2011 at 0:11
- thanks nybbler, guess I hadn't tried it that way. – Brandon Frohbieter Commented Feb 4, 2011 at 0:13
2 Answers
Reset to default 9There absolutely is! jQuery's .data()
.
$('#someId').data('myData', someValue); // To store the data
$('#someId').data('myData'); // To retrieve it again
Any JavaScript variable can be stored as data - it's not limited to strings.
Note that this doesn't actually attach data to the DOM node as you say (which should be avoided). jQuery keeps its own cache of all the data you store and the DOM nodes you wanted to attach it to. So, it's not the same as domNode.myData = someValue
.
jQuery.data is the preferred way of doing this.
本文标签: javascriptan alternative to hiding data in divsStack Overflow
版权声明:本文标题:javascript - an alternative to hiding data in divs? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742365895a2461235.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论