我很高兴html5 data attribute存在。
我可以将一个简单的字符串写入html属性并通过jquery访问它们。
但是....拥有超过一个简单的字符串会不会很好?
是否无法将JSON编码为这些数据属性。
在我目前的用例中,我需要在html5数据属性中存储字符串列表。
答案 0 :(得分:1)
<div id ="test" data-something='{"something":"something"}'></div>
data-attribute中的字符串会自动转换为JavaScript对象。
你可以在这样的javascript中访问它。
var somethingObject = $("#test").data("something");
var jsonSomethingObject = JSON.stringify(somethingObject);
console.log(somethingObject); //this will print the main javascript object
console.log(jsonSomethingObject);// this will print stringify javascript object
您可以参考相同的代码段
var someObject = $("#test").data("student");
var jsonData = JSON.stringify(someObject);
$('#display').text("id:"+someObject.id +" name:"+someObject.name)
console.log(someObject);
console.log(jsonData);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test" data-student='{"name": "Dhiraj", "id": 1}' />
<div id="display"></div>
答案 1 :(得分:0)
您可以将json作为字符串放在data
属性中,然后使用JSON.parse()
来获取它。
答案 2 :(得分:0)
好像你可以使用JSON.stringify
$("#ele").attr('data-example', JSON.stringify(new Array('1', '2')));
console.log($("#ele").attr('data-example'));
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='ele' data-example="nothing"></div>
&#13;
答案 3 :(得分:0)
您可以在data-
属性中存储JSON字符串。
function onPClick(evt) {
var special = evt.target.getAttribute('data-special');
if (special != null) {
try {
console.log("JSON", JSON.parse(special));
} catch (error) {
console.log("STANDARD", special);
}
} else {
console.log("NULL");
}
}
var ps = document.getElementsByTagName("p");
for (var pi = 0; pi < ps.length; pi++) {
var p = ps[pi];
p.onclick = onPClick;
}
<p>I am special!</p>
<p data-special='YES!'>I am special!</p>
<p data-special='{"a":"bob"}'>I am special!</p>
为了分离关注点,将数据保存在每次更改时都不必更新HTML的位置会更漂亮:
var p = document.body.appendChild(document.createElement("p"));
p.innerHTML = "Click me!";
Object.defineProperty(p, 'mySuperSecretValue', {
value: 37,
writable: true,
enumerable: true,
configurable: true
});
p.onclick = function pclick(evt) {
console.log(evt.target.mySuperSecretValue++, evt.target.outerHTML);
};