以京东代码为例:
对应代码:
从图中可以看出增加减函数都写在了一个对象setAmount中
var setAmount = { min: 1, max: 999, urlPerfix: "http://gate.360buy.com/InitCart.aspx?", targetLink: $("#choose-btn-append .btn-append"), data: { pid: G.sku, pcount: $("#buy-num").val(), ptype: 1 }, reg: function(a) { return new RegExp("^[1-9]\\d*$").test(a) }, amount: function(b, c) { var a = $(b).val(); if (this.reg(a)) { if (c) { a++ } else { a-- } } else { alert("\u8bf7\u8f93\u5165\u6b63\u786e\u7684\u6570\u91cf\uff01"); $(b).val(1); $(b).focus() } return a }, reduce: function(b) { var a = this.amount(b, false); if (a >= this.min) { $(b).val(a) } else { alert("\u5546\u54c1\u6570\u91cf\u6700\u5c11\u4e3a" + this.min); $(b).val(1); $(b).focus() } if (this.data.pcount) { this.data.pcount = $("#buy-num").val() } this.updateBuyLink(G.sku, this.urlPerfix) }, add: function(b) { var a = this.amount(b, true); if (a <= this.max) { $(b).val(a) } else { alert("\u5546\u54c1\u6570\u91cf\u6700\u591a\u4e3a" + this.max); $(b).val(999); $(b).focus() } if (this.data.pcount) { this.data.pcount = $("#buy-num").val() } this.updateBuyLink(G.sku, this.urlPerfix) }, modify: function(b) { var a = $(b).val(); if (a < this.min || a > this.max || !this.reg(a)) { alert("\u8bf7\u8f93\u5165\u6b63\u786e\u7684\u6570\u91cf\uff01"); $(b).val(1); $(b).focus() } if (this.data.pcount) { this.data.pcount = $("#buy-num").val() } this.updateBuyLink(G.sku, this.urlPerfix) }, updateBuyLink: function(f, a) { var c = this.data.pcount; var b = /^[0-9]{1,4}$/; var d = a || "http://gate.360buy.com/InitCart.aspx?"; if (!b.exec(c)) { c = 1 } else { if (c <= 0) { c = 1 } if (c >= 1000) { c = 999 } } if (typeof RecoServices.cacheData.ybId !== "undefined") { this.targetLink.attr("href", d + $.param(this.data) + "&ybId=" + RecoServices.cacheData.ybId) } else { this.targetLink.attr("href", d + $.param(this.data)) } } };
从代码中可以看出,相同的代码和配置参数都写在一个对象里,这样好管理