Alternative jQuery.data ()?

I am a big fan of the jQuery.data () method, but I can’t always use it. Often I process html templates that I pass through AJAX, and I need to attach metadata to each element in the template. For instance:

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

I know that attaching attributes to store data is bad practice (and this may not even work in older versions of IE). What is the best practice? Is there a good alternative to this method?

+3
source share
3 answers

, ( , ) javascript, , - .

:

<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>
+2

I think that the practice of adding classes that have no purpose other than the provision of metadata, is beautiful, and it seems that the creators jQueryUI (see. .ui-state-error, .ui-state-highlight, .ui-state-activeEtc.), but I do not know if it's right for you is bad practice .

+1
source

Source: https://habr.com/ru/post/1747242/


All Articles