使用数据存储和检索数据时无输出

时间:2015-01-22 09:41:16

标签: jquery

我是JS的新手,并把我的手放在JS中。使用数据存储和检索html中的数据时,我没有数据 - *。

<!DOCTYPE html>
<html>
<body>

<script>
$('#myElId').data('nameYourData', { foo: 'bar' });

var myData = $('#myElId').data('nameYourData');
document.write(myData);
</script>

</body>
</html> 

1 个答案:

答案 0 :(得分:0)

你的意思是

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Here is YOUR script - it needs its own set of script tags -->
<script>
$(function() { // on page load
  $('#myElId').data('nameYourData', { foo: 'bar' });
  // and later  
  var myData = $('#myElId').data('nameYourData');
  $("#showMyData").text(myData.foo);
});
</script>
</head>
<body>
<div id="myElId">Some element</div>
<div id="showMyData"></div>
</body>
</html> 

运行示例

$(function() { // on page load
  $('#myElId').data('nameYourData', { foo: 'bar' });
  // and later  
  var myData = $('#myElId').data('nameYourData');
  $("#showMyData").text(myData.foo);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="myElId">Some element</div><br/>
MyData:<div id="showMyData"></div>

阵列:

$(function() { // on page load
  $('#myElId').data('nameYourData', ["foo","bar"]);
  // and later  
  var myData = $('#myElId').data('nameYourData');
  $("#showMyData").text(myData);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="myElId">Some element</div><br/>
MyData:<div id="showMyData"></div>