1 回答
TA贡献2037条经验 获得超6个赞
换了个思路,功能已实现,代码如下:
<script>
var localNum = localStorage.getItem('#buyNum');
window.onload = function () {
if(localNum == null || localNum == '' || localNum == 'null' || localNum.length == 0 || localNum == undefined || localNum == 'undefined'){
var num = new Num(1)
}else{
var num = new Num(localNum)
}
num.initFn()
}
var Num = function (init) {
this.init = init
}
// 初始化
Num.prototype.initFn = function () {
var _this = this
this.showNum(this.init)
document.querySelector('#spSub').addEventListener('click', function() {
_this.prevClick()
})
document.querySelector('#spAdd').addEventListener('click', function() {
_this.nextClick()
})
document.querySelector('#buyNum').addEventListener('input', function(e) {
_this.inputBind(e)
})
}
// 显示数字
Num.prototype.showNum = function (val) {
document.querySelector('#buyNum').value = val
}
// - 按钮
Num.prototype.prevClick = function () {
if (this.init > 0) {
this.init--
if(this.init != localStorage.getItem('#buyNum')){
localStorage.setItem('#buyNum', this.init);
};
}
this.showNum(this.init)
}
// + 按钮
Num.prototype.nextClick = function () {
this.init++
if(this.init != localStorage.getItem('#buyNum')){
localStorage.setItem('#buyNum', this.init);
};
this.showNum(this.init)
}
// input 值绑定
Num.prototype.inputBind = function (e) {
var num = e.target.value
var input = document.querySelector('#buyNum')
if (num === '' || num === null) {
input.value = this.init
return false
}else{
input.value = input.value
localStorage.setItem('#buyNum', input.value);
}
var reg = /^[0-9]*$/
if (!reg.test(num)) {
input.value = this.init
return false
}
}
</script>
有兴趣的可以跑代码试试,不要说什么插件之类的,自己引入jq和bootstrap,加上问题中的style和body代码,代码有些繁琐,因为要做本地存储。
添加回答
举报