我很高兴 html5 数据属性存在。
我可以将一个简单的字符串写入 html 属性并通过 jquery 访问它们。
但。。。。拥有不止一个简单的字符串不是很好吗?
是否无法将 JSON 编码为这些数据属性。
在我当前的用例中,我需要在 html5 数据属性中存储字符串列表。
<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>
json 作为字符串放入data
属性中并使用JSON.parse()
来获取它。
似乎您可以使用JSON.stringify
$("#ele").attr('data-example', JSON.stringify(new Array('1', '2')));
console.log($("#ele").attr('data-example'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='ele' data-example="nothing"></div>
JSON 字符串存储在data-
属性中。
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);
};