小白一枚,我为每个选项标签都定义好了一个事件,而每个选项标签需要有个data-的自定义属性来记录用户是否有点击操作,但是在js代码中,要为每个选项标签定义一个响应函数,这样的代码过于冗余且后期不好维护,各位大佬们有什么好办法来简化js代码吗?
尝试过封装成函数,但在微信js文件的sdk不被允许。
<!--wxml-->
<text bindtap='chcolor' style='background-color:{{color}};color:{{tcolor}}' data-color="{{select}}">知识提问</text>
<text bindtap='chcolor2' style='background-color:{{color2}};color:{{tcolor2}}' data-color2="{{select2}}">日常</text>
<text bindtap='chcolor3' style='background-color:{{color3}};color:{{tcolor3}}' data-color3="{{select3}}">社交</text>
<text bindtap='chcolor4' style='background-color:{{color4}};color:{{tcolor4}}' data-color4="{{select4}}">周边推荐</text>
// js
chcolor: function (e) {
var bgcolor = e.target.dataset.color
console.log(bgcolor)
if (bgcolor == undefined || bgcolor == false) {
this.setData({ color: '#78ff85', select: true, tcolor: 'white' })
}
if (bgcolor == true) {
this.setData({ color: '#e0e3da57', select: false, tcolor: 'black' })
}
},
chcolor2: function (e){
var bgcolor2 = e.target.dataset.color2
if (bgcolor2 == undefined || 'false') {
this.setData({ color2: '#78ff85', select2: 'true', tcolor2: 'white' })
}
if (bgcolor2 == 'true') {
this.setData({ color2: '#e0e3da57', select2: 'false', tcolor2: 'black' })
}
} ,
chcolor3: function (e) {
var bgcolor3 = e.target.dataset.color3
if (bgcolor3 == undefined || 'false') {
this.setData({ color3: '#78ff85', select3: 'true', tcolor3: 'white' })
}
if (bgcolor3 == 'true') {
this.setData({ color3: '#e0e3da57', select3: 'false', tcolor3: 'black' })
}
} ,
chcolor4: function (e) {
var bgcolor4 = e.target.dataset.color4
if (bgcolor4 == undefined || 'false') {
this.setData({ color4: '#78ff85', select4: 'true', tcolor4: 'white' })
}
if (bgcolor4 == 'true') {
this.setData({ color4: '#e0e3da57', select4: 'false', tcolor4: 'black' })
}
} ,