开发者

Alternative to jQuery .data()?

I'm a big fan of jQuery's .data() method, but I can't always use it. Often times I am rendering html templates that I pass via AJAX and I need to attach metadata to each of the elements in the template. For example:

<ul>
{% for item in itemlist %}
    <li metadata="{{ item.metadata }}">{{ item.name }}</li>
{% endfor %}
</ul>

I know attaching attributes to store data is bad practice (and it might not even work in older versions of IE). What is the best pra开发者_如何学编程ctice? Is there a good alternative to this method?


data-* attributes. See Can I just make up attributes on my HTML tags?.


If the elements in question all have ids, then have (whatever server-side language that is) inject them into a javascript array, where the ids are the keys, and the metadata the values.

Example:

<script type="text/javascript">
    var metadata;
    {% for item in itemlist %}
        metadata['{{ item.id }}'] = '{{ item.metadata }}';
    {% endfor %}
    //metadata contains a set of id => metadat pairs
</script>

<ul>
    {% for item in itemlist %}
    <li id="{{ item.id }}">{{ item.name }}</li>
    {% endfor %}
</ul>


I think the practice of attaching classes that serve no purpose other than to provide metadata is fine, and so do the makers of jQueryUI it seems (see: .ui-state-error, .ui-state-highlight, .ui-state-active, etc), but I don't know if that qualifies as bad practice for you.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜