jquery .map() 和 .each()函数结合使用

时间:2023-03-08 20:23:31
jquery .map() 和 .each()函数结合使用

需求:页面动态添加的html元素(如div),保存时组装div中的数据为一个json对象。

思路:遍历每个div,再遍历div中每个输入元素,把所有先把数据放到一个对象中,再添加进数组,Json.stringfy()序列化。

简单效果图:

jquery .map() 和 .each()函数结合使用

点击加号“+”,可以动态添加。

function getCurrentCustomePrice() {
var cuspricelist = new Array();
_.map($("#tabLinePriceType .baojia"), function (n) {
var comment = {};
$(n).find("input").each(function () {
switch ($(this).attr("type")) {
//自定义报价类型
case "hidden":
comment.custypeid = $(this).val();
break;
case "checkbox":
if ($(this).val() == "0" && $(this).is(":checked")) {
comment.manprice = 1;
break;
}
else if ($(this).val() == "1" && $(this).is(":checked")) {
comment.childprice = 1;
break;
}
break;
case "text":
switch ($(this).attr("name").substring($(this).attr("name").lastIndexOf('.') + 1, $(this).attr("name").length)) {
case "price": //成人同行价
comment.price = $(this).val(); break;
case "pricechild": //儿童同行价
comment.pricechild = $(this).val(); break;
case "mprice": //成人市场价
comment.mprice = $(this).val(); break;
case "mpricechild": //儿童市场价
comment.mpricechild = $(this).val(); break;
case "sprice"://网上优惠价
comment.sprice = $(this).val(); break;
case "spricechild": //儿童网上优惠价
comment.spricechild = $(this).val(); break;
}
break;
}
});
cuspricelist.push(comment);  //加入数组
})
return cuspricelist;
}