【微信小程序】实现单选功能

废话不多说,先看效果

初始化


点击后



.wxml

< scroll-view class= 'bg' scroll-x= 'true' >
< view class= "item {{arry_now[index_s]==1?'active':''}}" wx:for= "{{array}}" wx:key= "index" wx:for-index= "index_s" bindtap= "click1" data-idx= "{{index}}" data-idx_s= "{{index_s}}" >
{{item.mag}}:{{index_s}} view >
scroll-view >


.wxss

.bg {
position: relative ;
white-space: nowrap ;
height: 100 rpx ;
border: 1px solid red ;
align-items: center ;
display: flex ;
justify-content: center ;
margin: 10px auto ;
}

.bg .item {
display: inline-block ;
width: 200 rpx ;
height: 50 rpx ;
text-align: center ;
line-height: 50 rpx ;
border: 1px solid #999 ;
margin-left: 20 rpx ;
position: relative ;
top: 25 rpx ;
}
.active {
color: red ;
}


.js

data : {
array : [],
arry_now : []

},

/**
* 生命周期函数--监听页面加载
*/
onLoad : function (options ) {
this .getData ();

},
getData : function () {
var that = this ;
console .log ( "getData" )
var data = [
{
id : 1 ,
mag : "111"

},
{
id : 2 ,
mag : "222"
},
{
id : 3 ,
mag : "333"
}, {
id : 4 ,
mag : "444"
}, {
id : 5 ,
mag : "555"
}, {
id : 6 ,
mag : "666"
}
, {
id : 7 ,
mag : "777"
}
]
var arry_now1 = [];

this .setData ({
array : data
})
for ( var i = 0 ; i < this .data .array .length ; i ++) {
console .log (i + "=*" + this .data .array [i ].select );
arry_now1 .push ( 0 );
}
arry_now1 [ 0 ] = 1 ;
console .log ( "==>" + arry_now1 )

this .setData ({
arry_now : arry_now1
})
console .log ( "==0>" + this .data .arry_now )

},
click1 : function (e ) {
var that = this ;
var idx = e .currentTarget .dataset .idx ,
idx_s = e .currentTarget .dataset .idx_s ;
console .log ( "idx==>" + idx )
console .log ( "idx_s==>" + idx_s )

for ( var i = 0 ; i < this .data .arry_now .length ; i ++) {
if (idx_s == i ) {
this .data .arry_now [i ] = 1 ;
} else {
this .data .arry_now [i ] = 0 ;
}
}
console .log ( this .data .arry_now )
this .setData ( this .data )
},



你可能感兴趣的:(小程序)