说明:微信小程序中,后台返回一个字符串(其中包含了手机号),我们需要将该手机号高亮且点击能够拨打电话。
PS:这里是通过自定义模拟一个字符串来实现
1.项目思路
将定义的字符串进行split
let list = desc.split(/(1\d{10})/);
获取到的数组进行循环判断是否是手机号
for(let i in list){
// 判断是否是手机号
let flag = list[i] != '' && /^(1\d{10})$/.test(list[i]);
// 不为空 添加到数据descList中,并且根据flag的值赋予属性是电话还是文字
list[i] != '' && descList.push({type: flag?'phone':'text','words': list[i]})
}
构建成数组展示
2.代码部分
.wxml
<view class="main">
<view class="content">
<block wx:for="{{descList}}" wx:key="index">
<text wx:if="{{item.type === 'text'}}">{{item.words}}</text>
<text wx:else class="active" bindtap="call" data-phone="{{item.words}}">{{item.words}}</text>
</block>
</view>
</view>
.wxss
.main{
background: #fff;
margin-top: 20rpx;
}
.main .content{
font-size: 28rpx;
line-height: 44rpx;
color: #333;
padding: 30rpx;
}
.main .content .active{
color: #ff0000;
}
.js
Page({
data: {
descList: null, // 分隔传入字符串的数组
},
async onLoad(options) {
let str = `
我的运输信息时买很多东西,你可以拨打18611111111或18711111111,另外还有备用联系电话18511111111真的很棒!
`;
const descList = await this.filterDesc(str);
this.setData({descList})
},
async filterDesc(desc){
let list = desc.split(/(1\d{10})/); // 验证手机号
let descList = []
for(let i in list){
// 判断是否是手机号
let flag = list[i] != '' && /^(1\d{10})$/.test(list[i]);
// 不为空 添加到数据descList中,并且根据flag的值赋予属性是电话还是文字
list[i] != '' && descList.push({type: flag?'phone':'text','words': list[i]})
}
return descList;
},
// 拨打电话
call(e){
wx.makePhoneCall({
phoneNumber: e.currentTarget.dataset.phone,
})
}
})
3.效果展示