如何获取小程序picker表单普通选择器的值

今天用小程序的picker组件时,遇到遇到了picker组件的坑,相信很多不仔细

看官方文档的同学们也会遇到,这里就简单记录下:

方文档上写了value是下标不是值;

value Number 0 value 的值表示选择了 range 中的第几个(下标从 0 开始)

官方提供的例子

console .log ( 'picker发送选择改变,携带值为' , e .detail .value )

打印结果如下:


官方这里有个误导,携带值让第一眼看到的人都以为这里

e.detail.value就是选中项的值,其实只是选中项的下标;

那么如何才能打印出值呢?

下面提供几种方法:

xml:

< view class= "section" >
< view class= "section__title" >普通选择器 </ view >
< picker bindchange= "bindPickerChange" value= "{{index}}" range= "{{array}}" >
< view class= "picker" >
当前选择:{{array[index]}}
</ view >
</ picker >
</ view >


js:

data : {
array : [ '夏彤' , '陈学华' , '甘广' , '黄龙流' , '李昌略' , '董俊辉' , '罗景盛' , '钟敏君' , '林锐' , '麦健发' , '曹兵' ],
objectArray : [
{
id : 0 ,
name : '夏彤'
},
{
id : 1 ,
name : '陈学华'
},
{
id : 2 ,
name : '甘广'
},
{
id : 3 ,
name : '黄龙流'
},
{
id : 4 ,
name : '李昌略'
},
{
id : 5 ,
name : '董俊辉 '
},
{
id : 6 ,
name : '罗景盛'
}
,
{
id : 7 ,
name : '钟敏君'
}
,
{
id : 8 ,
name : '林锐'
}
,
{
id : 9 ,
name : '麦健发'
}
,
{
id : 10 ,
name : '曹兵'
}
]







关键是这个函数:

方法1:

bindPickerChange : function (e ) {
var index = this .data .index //记得要声明的,不然打印是undifind
console . log ( 'picker发送选择改变,携带下标为' , e . detail . value )
console .log ( 'picker发送选择改变,携带值为' , this .data .array [index ])

this .setData ({
index : e .detail .value
})
},


方法2:

bindPickerChange : function (e ) {
console .log ( 'picker发送选择改变,携带下标为' , e .detail .value )
console .log ( 'picker发送选择改变,携带值为' , this .data.array [e .detail .value ])
this .setData ({
index : e .detail .value
})
},

打印结果如下:


edetail.v

猜你喜欢

转载自blog.csdn.net/weixin_39818813/article/details/80544499