HTML中的属性值有多长时间?
我data-foo="bar"在一个新的应用程序中使用HTML5样式的数据属性(),在一个地方存储数据的公平数据(超过100个字符)真的很方便.虽然我怀疑这个数量很好,但它提出了多少太多的问题?
我需要将一个JSON对象放入HTML元素的属性中.
HTML不必验证.
Quentin回答:将JSON存储在data-*属性中,该属性是有效的HTML5.
JSON对象可以是任何大小 - 即巨大的
由Maiku Mori回答:HTML属性的限制可能是65536个字符.
如果JSON包含特殊字符怎么办?例如 {foo: '<"bar/>'}
Quentin回答:根据通常的惯例,在将JSON字符串放入属性之前对其进行编码.对于PHP,请使用该功能. htmlentities()
编辑 - 使用PHP和jQuery的示例解决方案
将JSON写入HTML属性:
<?php
$data = array(
'1' => 'test',
'foo' => '<"bar/>'
);
$json = json_encode($data);
?>
<a href="#" data-json="<?php echo htmlentities($json, ENT_QUOTES, 'UTF-8'); ?>">CLICK ME</a>
Run Code Online (Sandbox Code Playgroud)
使用jQuery检索JSON:
$('a').click(function() {
// Read the contents of the attribute (returns a string)
var data = $(this).data('json');
// Parse the string back into a proper JSON object
var …Run Code Online (Sandbox Code Playgroud)