首先感谢你们点进来看。我的问题如下
- 有多个input的组建,每个都有一个bindinput的
- 因为每一个input都有bindinput,而且他们的功能都是类似的,目前的情况就是我有大量重复使用的字段。
Page({
data: {
inputValue1:'',
inputValue2:'',
inputValue3:'',
inputValue4:'',
},
input1: function (e) {
if (Math.abs(e.detail.value.length - this.data.inputValue1.length) != 1) {
this.setData({
inputValue1: ''
})
return ''
} else {
let reg = /^[0-9]*$/
if (!reg.test(e.detail.value)) {
this.setData({
inputValue1: ''
})
return ''
} else {
this.setData({
inputValue1:e.detail.value
})
}
}
},
input2: function (e) {
if (Math.abs(e.detail.value.length - this.data.inputValue2.length) != 1) {
this.setData({
inputValue2: ''
})
return ''
} else {
let reg = /^[0-9]*$/
if (!reg.test(e.detail.value)) {
this.setData({
inputValue2: ''
})
return ''
} else {
this.setData({
inputValue2:e.detail.value
})
}
}
},
})
如上述所见,每一个input的function其实只是改了inputValue1或inputValue2。所以我就想说能不能将他们集合到一个function里面。如下
checkInput: function (inputValue) {
if (Math.abs(e.detail.value.length - this.data.inputValue.length) != 1) {
this.setData({
inputValue: ''
})
return ''
} else {
let reg = /^[0-9]*$/
if (!reg.test(e.detail.value)) {
this.setData({
inputValue: ''
})
return ''
} else {
this.setData({
inputValue:e.detail.value
})
}
}
},
input1: function (e) {
this.checkInput(this.data.inputValue1)
},
input2: function (e) {
this.checkInput(this.data.inputValue1)
},
但是上述的这个情况却报错了,以下的这个错误
ReferenceError: e is not definedy
因为我也算是新手,所以如有不好的地方请大家多多包涵。在这里也希望大家能帮我看看哪里有问题。好让我缩短代码长度。
再次拜谢!
------------------------------------
试了一下楼下提醒我的,代码还是报错了。
input1: function (e) {
this.checkInput(e, this.data.inputValue1)
},
input2: function (e) {
this.checkInput(e, this.data.inputValue1)
},
主要问题出在了这几个地方。
if (Math.abs(e.detail.value.length - this.data.inputValue.length) != 1) {
this.setData({
inputValue: ''
})
这里第一行出现的是 this.data.inputValue.length 但是第三行出现的是 inputValue 如果我将第一行this.data.inputValue.length 换成 inputValue.length 代码就没有报错。 但是功能也实现不出来。
麻烦大家看看怎么解决比较好!辛苦大家了。
网友回复
番茄炖地蛋:
那就调用的时候,多加个参数,把e传过去就好了啊