微信小程序星级评分和展示

2,076 阅读1分钟

1、星级评分

wxml部分

<view style='margin-top:60px;'>显示用户选择的评分</view>
//点击已经点亮的星星(熄灭星星)
<block wx:for="{{starsCount}}" wx:key="index">
 <image catchtap='scoreStars' id='{{index+1}}' data-in='star' src='../../image/star.png'></image>
</block>
//点击已经熄灭的星星(点亮星星)
<block wx:for="{{noStars}}" wx:key="index">
 <image catchtap='scoreStars' id='{{index+1}}' data-in='starg' src='../../image/starg.png'></image>
</block>
<view>{{starsCount}}星</view>

wxss部分

image{ 
 height: 60rpx; 
 width: 60rpx; 
 display: inline-block
}

js部分

 data: {
  starsCount: 0,//点亮的星星数
  noStars: 5//没有点亮的星星数
 },
  //打分操作
 scoreStars: function (e) {
  var scoreStars = e.currentTarget.dataset.in;
  var starsCount;
  //如果是熄灭星星,点击到第几颗星则为几分
  if (scoreStars == 'star') {
   starsCount = Number(e.currentTarget.id)
  } 
  //如果是点亮星星,分值=当前点亮的星星数+当前的点击的第几个星星
  else {
   starsCount = Number(e.currentTarget.id) + this.data.starsCount
  }
  //更新视图
  this.setData({
   starsCount: starsCount,
   noStars: 5 - noStars
  })
 },

2、显示已经打的分数(后台传值)

wxml部分

<view>
 <view>一:显示后台给的评分</view>
 <block wx:for="{{starsCount}}" wx:key="item">
  <image src='../../image/star.png'></image>
 </block>
 <block wx:for="{{noStars}}" wx:key="item">
  <image src='../../image/starg.png'></image>
 </block>
</view>
<view>这里num给的是几分就显示几颗星星</view>

js部分

 /**
  * 页面的初始数据
  * 满分为5星
  */
 data: {
  num: 4,//后端给的分数,显示的星星
  starsCount: '',//点亮的星星数
  noStars: '',//没有点亮的星星数
 },
/**
  * 生命周期函数--监听页面加载
  */
 onLoad: function (options) {
  //展示后台给的评分 
  this.setData({
   starsCount: this.data.num,
   noStars: 5 - this.data.num
  })
 },