index.wxml
<view class="option-list"> <view class="option-item {{item.selected? 'selected' : ''}}" wx:for="{{optionList}}" wx:key="index" bindtap="toggleSelect" data-index="{{index}}"> {{item.text}} </view> </view>
这里假设数据是一个名为optionList
的数组,每个元素包含text
(显示的文本内容)和selected
(用于标记是否选中的布尔值)字段,通过wx:for
指令来循环渲染列表项,并且根据selected
的值来动态添加selected
类名(用于高亮显示),每个列表项绑定了toggleSelect
点击事件,并传递当前项的索引。
index.js
Page({ data: { optionList: [ { text: '选项1', selected: false }, { text: '选项2', selected: false }, { text: '选项3', selected: false } ] }, toggleSelect: function (e) { const index = e.currentTarget.dataset.index; const optionList = this.data.optionList; optionList[index].selected =!optionList[index].selected; this.setData({ optionList: optionList }); } })
在上述代码中,toggleSelect
函数是点击列表项时触发的事件处理函数,通过获取点击项的索引,然后对相应索引位置的selected
属性取反,来实现选中和取消选中的切换,最后通过setData
方法更新页面数据,使得页面根据新的selected
状态重新渲染,进而实现高亮显示选中项的效果。
如果是使用其他前端框架(如 Vue、React 等)开发小程序或者网页端类似功能,思路也是类似的,主要是在模板中实现列表渲染与动态类绑定,在样式中定义好相应状态的样式,以及在逻辑代码中处理好点击事件和数据更新的逻辑。
请注意,以上代码只是一个基础示例,实际应用中可能需要根据具体业务场景进行更多的拓展和优化,比如添加全选、反选等功能,或者和后端进行交互来保存选中的数据等。
index.wxss
.option-list { padding: 10px; } .option-item { border: 1px solid #ccc; padding: 10px; margin-bottom: 10px; } .option-item.selected { background-color: #f0f0f0; /* 这里定义高亮的背景色,可按需修改 */ color: #333; }