JSON对象转化

本文介绍了一个基于jQuery的插件,该插件提供了一种简单的方法来读取和设置DOM元素的数据。其中包括了用于获取指定标签数据的getData方法及用于设置数据的setData方法,并且支持JSON格式转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 1 (function ($) {
 2     $.fn.getData = function (itemTag) {
 3         var obj;
 4         if (itemTag) {
 5             obj = [];
 6             this.find(itemTag).each(function () {
 7                 obj.push($(this).getData());
 8             });
 9             return obj;
10         }
11         else {
12             obj = {};
13             this.find("input,select").each(function (i, v) {
14                 if (this.name) {
15                     obj[encodeURIComponent(this.name)] = encodeURIComponent($.trim($(this).val()));
16                 }
17             });
18             return obj;
19         }
20     };
21     $.fn.setData = function (obj) {
22         if ($.isPlainObject(obj)) {
23             for (var p in obj) {
24                 var element = $('input[name="' + decodeURIComponent(p) + '"]' + ',select[name="' + decodeURIComponent(p) + '"]');
25                 if (element.length > 0 && !$.isArray(obj[p])) {
26                     element.val(decodeURIComponent(obj[p]));
27                 }
28             }
29         }
30     };
31 })(jQuery);
32 $.extend({
33     toJSON: function (obj) {
34         if ($.isPlainObject(obj)) {
35             var props = [];
36             for (var p in obj) {
37                 var prop = obj[p];
38                 var propStr = '';
39                 if ($.isArray(prop)) {
40                     propStr += '[';
41                     var items = [];
42                     $.each(prop, function (i, v) {
43                         if ($.type(v) == "number" || $.type(v) == "string") {
44                             items.push('"' + v + '"');
45                         }
46                         else {
47                             items.push($.toJSON(v));
48                         }
49                     });
50                     propStr += items.join(',') + ']';
51                 }
52                 else {
53                     propStr += '"' + prop + '"';
54                 }
55                 props.push('"' + p + '":' + propStr);
56             }
57         }
58         return '{' + props.join(',') + '}';
59     }
60 });

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值