通用例遍方法,可用于例遍对象和数组。
不同于例遍 jQuery 对象的 $().each() 方法,此方法可用于例遍任何对象。回调函数拥有两个参数:第一个为对象的成员或数组的索引,第二个为对应变量或内容。如果需要退出 each 循环可使回调函数返回 false,其它返回值将被忽略。
object:需要例遍的对象或数组。 callback:每个成员/元素执行的回调函数。
jQuery 代码:
$.each( [0,1,2], function(i, n){ alert( "Item #" + i + ": " + n ); });
实例:
json = JSON.parse(json); opt_str = "<option value=''>-请选择-</option>" if (json.status == 1) { $.each(json.data, function(index, con) { opt_str += "<option value=" + con.id + ">" + con.name + " 电话:" + con.tel + "</option>" }) } $('#agent_id').html(opt_str);
获取json数据,进行处理。
json返回数据
{"status":1,"info":"","data":[{"id":"3","name":"u5bbfu8fc1u4ee3u7406u5546","tel":"15262731823"},{"id":"18","name":"u4ee3u7406u5546u5f20u601d","tel":"15850946234"}]}
效果