静态购物车

静态购物车

// 购物车 数量增减
// numEle-存放数量的元素 input可手动输入,此处判断了 存放元素的标签类型 ##

js封装

var ShoppingCart = function (opt) {
    var _default = {
        addEle: null,  // 数量加按钮
        reduceEle: null,   // 数量减按钮,
        numEle: null,      // 存放数量的元素
        maxNum: null        //  最大值
    }
    this._opation = $.extend({}, _default, opt)
    this.initnum = 1;
    this.init()
}
ShoppingCart.prototype = {
    init: function () {
        let $this = this
        var tagType = this._opation.numEle[0].tagName.toLowerCase();
        vals($this.initnum)  // 默认 1
        var currentNum;
        this._opation.addEle.click(function () {

            currentNum = tagType == 'input' ? $this._opation.numEle.val() - 0 : $this._opation.numEle.html() - 0;
            currentNum += 1;
            if ($this._opation.maxNum != null && currentNum > Number($this._opation.maxNum)) {
                currentNum = Number($this._opation.maxNum);
            }
            vals(currentNum)
        })
        this._opation.reduceEle.click(function () {
            currentNum = tagType == 'input' ? $this._opation.numEle.val() - 0 : $this._opation.numEle.html() - 0;
            currentNum -= 1;
            if (currentNum <= 0) {
                currentNum = 1;
            }
            vals(currentNum)
        })
        // 手动输入数值判断 是否合法 不合法则让其等于最大值
        this._opation.numEle.keyup(function () {
            currentNum = $this._opation.numEle.val() - 0;
            if ($this._opation.maxNum != null && currentNum > Number($this._opation.maxNum)) {
                currentNum = Number($this._opation.maxNum);
            }
            vals(currentNum)
        })
        function vals(num) {
            if (tagType == 'input') {
                $this._opation.numEle.val(num);
            } else {
                $this._opation.numEle.html(num);
            }
        }

    }
}

用法

var g = new ShoppingCart({
    addEle: $('.add'), // 数量加按钮
    reduceEle: $('.reduce'), // 数量减按钮,
    numEle: $('.inputCard'), // 存放数量的元素
    maxNum: 20 //  最大值
})
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.

扫一扫,分享到微信

微信分享二维码
  • Copyrights © 2015-2021 魏姣
  • Visitors: | Views:

请我喝杯咖啡吧~

支付宝
微信