经常在商城或汽车系统里可以看到很多商品对比或车型对比的页面,最近做项目也遇到了这样的需求,想到了一种实现思路,如果大家有什么更好的办法,不惜赐教。
1.实现基础:扩展prototype,实现通过索引来访问Josn对象属性字段。
<script type="text/javascript">
Object.prototype.k = function (n, t) {
var arr = [];
for (pro in this) arr.push(pro);
return t ? arr[n] : this[arr[n]]
}
var jsonObject = { "UserID": 11, "Name": { "FirstName": "John", "LastName": "Hansen" }, "Email": "[email protected]" };
var b = { b: { bb: { bbb: { bbbb: '22'}}} }
alert(jsonObject.k(0, 1)) //取属性带2个参数
alert(jsonObject.k(0)) //取直就只带一个参数
alert(b.k(0).k(0).k(0).k(0, 1))
alert(b.k(0).k(0).k(0).k(0))
</script>
2.思路分析:这里的内容对比,假定对比的字段都是固定的,也就是说参与对比的几个对象所拥有的字段都是一样的。
①建好对比内容框架,固定表格对比字段,比如像这样:
<table width="100%" class='border' border="0" cellpadding="2" cellspacing="1">
<tr>
<td id='field_r0_c0'>
对比字段1
</td>
<td>
<span id='field_r0_c1'></span>
</td>
<td>
<span id='field_r0_c2'></span>
</td>
<td>
<span id='field_r0_c3'></span>
</td>
<td>
<span id='field_r0_c4'></span>
</td>
</tr>
<tr>
<td id='field_r1_c0'>
对比字段2
</td>
<td>
<span id='field_r1_c1'></span>
</td>
<td>
<span id='field_r1_c2'></span>
</td>
<td>
<span id='field_r1_c3'></span>
</td>
<td>
<span id='field_r1_c4'></span>
</td>
</tr>
<tr>
<td id='field_r2_c0'>
对比字段3
</td>
<td>
<span id='field_r2_c1'></span>
</td>
<td>
<span id='field_r2_c2'></span>
</td>
<td>
<span id='field_r2_c3'></span>
</td>
<td>
<span id='field_r2_c4'></span>
</td>
</tr>
<tr>
<td id='field_r3_c0'>
对比字段4
</td>
<td>
<span id='field_r3_c1'></span>
</td>
<td>
<span id='field_r3_c2'></span>
</td>
<td>
<span id='field_r3_c3'></span>
</td>
<td>
<span id='field_r3_c4'></span>
</td>
</tr>
<tr>
<td id='field_r4_c0'>
对比字段5
</td>
<td>
<span id='field_r4_c1'></span>
</td>
<td>
<span id='field_r4_c2'></span>
</td>
<td>
<span id='field_r4_c3'></span>
</td>
<td>
<span id='field_r4_c4'></span>
</td>
</tr>
</table>
这里通过col和row分别对应Josn对象里的第几个对象的第几个字段。
②通过ajax方式,取得将要对比的内容的Josn数据格式。
③通过对Josn对象的分析,利用Js循环为每个单元格赋值,伪代码:
for (var r = 0; r <fieldCount ; r++) { //fieldCount 对比Josn对象的字段数
for (var c = 1; c < cmpList.Length; c++) { //cmpList对比Josn集合
elem = "#field_r" + r + "_c" + c;
$(elem).html(cmpList[c][r]); //第几个对象的地几个字段值
}
}
2011年9月19日17:26:58 附加:
更好的遍历Josn的方法,利用jquery的each方法:
var arr1 = [ "one", "two", "three", "four", "five" ];
$.each(arr1, function(){
alert(this);
});
输出:one two three four five
var arr2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
$.each(arr2, function(i, item){
alert(item[0]);
});
输出:1 4 7
var obj = { one:1, two:2, three:3, four:4, five:5 };
$.each(obj, function(key, val) {
alert(obj[key]);
});
输出:1 2 3 4 5
写了几个例子,运行一下看看就明白啦!很简单吧!