JS

  1. var pageData = {
  2. data: {
  3. switch1Checked: true,
  4. switch2Checked: false,
  5. switch1Style: '',
  6. switch2Style: 'text-decoration: line-through'
  7. }
  8. }
  9. for (var i = 1; i <= 2; ++i) {
  10. (function (index) {
  11. pageData[`switch${index}Change`] = function (e) {
  12. console.log(`switch${index}发生change事件,携带值为`, e.detail.value)
  13. var obj = {}
  14. obj[`switch${index}Checked`] = e.detail.value
  15. this.setData(obj)
  16. obj = {}
  17. obj[`switch${index}Style`] = e.detail.value ? '' : 'text-decoration: line-through'
  18. this.setData(obj)
  19. }
  20. })(i)
  21. }
  22. Page(pageData)

XML

  1. <view class="page">
  2. <view class="page__hd">
  3. <text class="page__title">switch</text>
  4. <text class="page__desc">开关</text>
  5. </view>
  6. <view class="page__bd">
  7. <view class="section section_gap">
  8. <view class="section__title">type="switch"</view>
  9. <view class="body-view">
  10. <switch checked="{{switch1Checked}}" bindchange="switch1Change"/>
  11. </view>
  12. </view>
  13. <view class="section section_gap">
  14. <view class="section__title">type="checkbox"</view>
  15. <view class="body-view">
  16. <switch type="checkbox" checked="{{switch2Checked}}" bindchange="switch2Change"/>
  17. </view>
  18. </view>
  19. </view>
  20. </view>