我注意到在表示从服务器传递的 DOM 中的字符串作为 HTML 属性或全局变量方面存在一些差异。
有一个字符串是 JSON 编码的对象,其中包含特殊字符,并按以下方式设置此字符串:
<div id="my-id"
data-opt='[{"id":"600900340","parent_id":"600900000","name":"\tCollector\u0027s Cars \u0026 Models","visible":"1","level":"3"}]'
></div>
<script>
window.opt = '[{"id":"600900340","parent_id":"600900000","name":"\tCollector\u0027s Cars \u0026 Models","visible":"1","level":"3"}]';
</script>
现在用 js 检查它们:
;(function(window) {
console.log(document.getElementById('my-id').dataset.opt);
console.log(window.opt);
}(window))
输出:
[{"id":"600900340","parent_id":"600900000","name":"\tCollector\u0027s Cars \u0026 Models","visible":"1","level":"3"}]
[{"id":"600900340","parent_id":"600900000","name":" Collector's Cars & Models","visible":"1","level":"3"}]
为什么它们不同?
这是jsfiddle http://jsfiddle.net/9ss5M/3/