微信小程序点击分类标签能有对应的显示
作者:野牛程序员:2023-11-14 10:33:16小程序阅读 2846
点击分类时能够正确触发事件。请参考以下示例:
页面结构(WXML):
<!-- pages/index/index.wxml --> <view class="container"> <view class="category-list"> <view wx:for="{{categories}}" wx:key="index" class="category-item" data-id="{{item.id}}" bindtap="onCategoryTap"> {{item.name}} </view> </view> <view class="selected-category"> <text>当前选择:{{selectedCategory.name}}</text> </view> </view>
// pages/index/index.js Page({ data: { categories: [ { id: 1, name: '分类1' }, { id: 2, name: '分类2' }, { id: 3, name: '分类3' }, // Add more categories as needed ], selectedCategory: {}, }, onCategoryTap: function (event) { const categoryId = event.currentTarget.dataset.id; const selectedCategory = this.data.categories.find(category => category.id === categoryId); this.setData({ selectedCategory: selectedCategory, }); }, });
添加了 data-id="{{item.id}}"
到分类项目的 view
元素中,并在 bindtap="onCategoryTap"
中引用了这个 data-id
。这样,当用户点击分类时,onCategoryTap
函数会正确获取被点击分类的 id
并更新 selectedCategory
。
样式(WXSS):
/* pages/index/index.wxss */ .container { display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100vh; } .category-list { display: flex; flex-wrap: wrap; justify-content: space-around; width: 80%; } .category-item { margin: 10px; padding: 10px; border: 1px solid #ddd; border-radius: 5px; cursor: pointer; } .selected-category { margin-top: 20px; }
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892
- 上一篇:用turtle绘制叠加等边三角形
- 下一篇:form表单中的action属性