我有一个数组,我将使用 PHP回显一个页面,我希望JQuery能够解析它.但是,我不希望数据必须对用户可见.我有,例如: div id="data-1" span id="width"5/span span id="height"10/span span id="depth"15/span/divdiv
<div id="data-1">
<span id="width">5</span>
<span id="height">10</span>
<span id="depth">15</span>
</div>
<div id="data-2">
<span id="width">10</span>
<span id="height">20</span>
<span id="depth">30</span>
</div>
我想知道我是否应该以这种方式存储数据,然后在JQuery中,隐藏它们onload并通过稍后获取span值来播放数据:
$(document).ready( function() {
$("#width, #height, #depth").hide();
$("#data-*").click(function() {
var width = $("#width", $(this)).text();
var height = $("#height", $(this)).text();
var depth = $("#depth", $(this)).text();
});
});
这是在页面上存储数据的最有效方法吗?我应该使用隐藏的输入,还是有其他方法可以做到这一点?
当您使用PHP回显数据时,将其传递给 json_encode(),这将生成一个可以由jQuery本机读取的javascript对象.然后,您可以在发出请求时将其插入页面底部,或使用AJAX即时获取.PHP:
$my_data = array(
'data1' => array(
'width' => 16,
'height' => 20
),
'data2' => array(
'width' => 16,
'height' => 20
)
);
# echo at bottom of page
echo '<script type="text/javascript">';
echo 'window.my_data = '.json_encode($my_data);
echo '</script>';
jQuery的:
var height = window.my_data.data1.height
