js编程思路--把相同功能的代码,配置放到一个对象里

以京东代码为例:

对应代码:

从图中可以看出增加减函数都写在了一个对象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))
        }
    }
};

从代码中可以看出,相同的代码和配置参数都写在一个对象里,这样好管理

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值