将HTML标记中的数据存储为自定义属性

roo*_*ook 3 html zpt template-tal

将相关信息存储在HTML标签中是一种很好的做法吗?

$("#my_div").append("<span id='info' boo='foo'/>");
$("#info").attr("boo");
Run Code Online (Sandbox Code Playgroud)

我在TAL(in ZPT)中遇到过这样的技术(稍微借用它),你可以使用tal:attributes语句来修改HTML标签(例如,boo从后端传递变量的值,作为属性值在最终文档中呈现):

<span id='info' tal:attributes='boo view/boo'>
Run Code Online (Sandbox Code Playgroud)

结果:

<span id='info' boo='foo'>
Run Code Online (Sandbox Code Playgroud)

这种技术有一天会破坏文档,还是规范安全?

Kei*_*man 12

正确的方法是使用data-*属性:

http://www.w3.org/TR/2011/WD-html5-20110525/elements.html#embedding-custom-non-visible-data-with-the-data-attributes

在切向上,jQuery也有一种特殊的方法来处理这些问题.例如:

<p id='string' data-user_name='thedude'></p>
$('#string').data('user_name') => "thedude"
typeof $('#string').data('name') => "string"

<p id='number' data-user_id='12345'</p>
typeof $('#number').data('user_id') => "number"

<p id='boolean' data-user_is_active='true'></p>
typeof $('#boolean').data('user_is_active') => "boolean"

<p id = 'json' data-user='{"name": "the dude", "id": "12345"}'></p>
typeof $('#json').data('user') => "object"
// embedding JSON is extremely useful in my experience
Run Code Online (Sandbox Code Playgroud)