在Vue或小程序中利用元素的id的不同来判断给哪个添加样式。

在Vue中
1. <div id="app">
2. <h1>Vue中制作单选、多选点击变色教程</h1>
3. <h2>原文地址:<a href="https://blog.bg7zag.com/rOdt5">https://blog.bg7zag.com/rOdt5</a></h2>
4.
5. <h2>单选</h2>
6. <ul>
7. <li v-for="item in phones" :key="item.id" :class="radio == item.id ? 'bgColor':'' " @click="clickRadio(item.id)">{{item.name}}</li>
8. <div class="clean"></div>
9. </ul>
10.
11. <h2>多选</h2>
12. <ul>
13. <li v-for="items in phones" :class="Checkbox.includes(items.id) ? 'bgColor':'' " @click="clickCheckbox(items.id)">{{items.name}}</li>
14. <div class="clean"></div>
15. </ul>
16. </div>
17. <script src="https://cdn.jsdelivr.net/npm/vue"></script>
18. <script>
19. var app = new Vue({
20. el: '#app',
21. data: {
22. // 定义一个变量 用于储存id 单选只储存一个使用字符串
23. radio:'',
24.
25. // 多选储存多个id 则使用数组
26. Checkbox:[],
27.
28. phones:[
29. {
30. id:1,
31. name:'华为',
32. },
33. {
34. id:2,
35. name:'荣耀',
36. },
37. {
38. id:3,
39. name:'小米',
40. },
41. {
42. id:4,
43. name:'魅族',
44. },
45. {
46. id:5,
47. name:'OPPO',
48. },
49. {
50. id:6,
51. name:'vivo',
52. },
53. ]
54. },
55. methods:{
56. clickRadio:function(e){
57. if(this.radio == e){
58. // 如果已经点击则取消点击样式
59. this.radio = ''
60. }
61. else{
62. // 把点击的元素id放入radio中
63. this.radio = e;
64. }
65.
66. },
67. clickCheckbox:function(e){
68. if(this.Checkbox.includes(e)){
69. this.Checkbox.splice(this.Checkbox.indexOf(e),1);
70. }else{
71. // 把点击的元素id放入Checkbox数组中
72. this.Checkbox.push(e);
73. }
74. }
75. }
76. })
77.
78. </script>
在小程序中
在小程序中的原理也是和Vue中一样,只是设置数据的方式不一样而已,Vue中直接使用 this.radio = e ,但在小程序中则是
1. this.setData({
2. radio:e
3. })
PS: (2018-02-08) 小程序的多选不能这样做,如果点击执行请求的话,则从请求中获取状态码判断是否被选中( {{item.checkbox == 1?'bgColor':''}} );
如果没有执行请求的话,可以在预设data中的phones数组中添加状态码。
1. <text wx:for="{{TFtips}}" id='{{item.id}}' wx:key="{{item.id}}" data-index="{{index}}" bindtap='color_green' class="{{item.checked?'bgColor':''}}">{{item.name}}</text>
data中的数组 {id:1,name:'华为',checked:false}, js中这样写:
1. color_green:function(e){
2. // console.log(e.currentTarget.dataset.index)
3. let index = e.currentTarget.dataset.index;
4. let phones = this.data.phones
5. let that = this;
6. phones[index].checked = !phones[index].checked
7. this.setData({
8. phones:phones
9. })
10. },
演示demo