jquery - HTML 数据属性值 jQuery 对象

标签 jquery html json

如何通过 $.param 将 HTML 属性值用作 JQuery 对象?

<div data-sd="{a:1,b:1,c:2}"></div>

当我尝试这个时,我得到了奇怪的结果。

<script type="text/javascript">
var v = $.param($('div').data('sd'));
</script>

最佳答案

双引号将对象的属性名称括起来,以便格式良好 JSON :

<div data-sd='{"a":1,"b":1,"c":2}'></div>​​​​​​​​​​​​​​​​​​​

然后,$.param 将按预期返回 a=1&b=1&c=2。 <强> DEMO

来自HTML5 data-* Attributes :

When the data attribute is an object (starts with '{') or array (starts with '[') then jQuery.parseJSON is used to parse the string; it must follow valid JSON syntax including quoted property names.

关于jquery - HTML 数据属性值 jQuery 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12437928/

相关文章:

Jquery Keyup 函数之间的延迟

javascript - 使用单击图像映射更改设置为背景的 Sprite 图像的位置

jquery - 如何在 Bootstrap 下拉菜单项上添加与父项相同的宽度

html - CSS/HTML : Create a glowing border around an Input Field

javascript - 导入 json 文件时的 Typescript 编译器错误

javascript - 如何设置 setTimeout 和clearTimeout 在同一按钮上运行

javascript - 如何制作一个从底部平滑扩展到视口(viewport) 85% 的 div?

html - CSS 中的固定页脚效果(如固定图像)

php - 如何将 json 从 PHP 传递到 AngularJS

javascript - 在 JSON/Javascript 中表示时间的首选方式?