<p>在微信开发中我们经常会用到标签中属性的属性值,有时候我们通过 data-* 和 e.target.dateset 来获取属性值会出现一点小bug,即是调用出来的数据是undefined。</p><p> 1)方案1–去掉驼峰式命名,纯小写</p><pre class="brush:bash;toolbar:false"><--HTML写法:-->
<buttonbinTap="buy"data-textId="101"></button>
//JS调用:
buy:function(e){
console.log(e.target.dataset.textId);
//输出结果:undefined
}</pre><p> 很多人可能会像我我一样卡在这里了,怎么找都找不到原因,怎么更改都是undefined。</p><p> 其实,很简单!</p><p> 那就是data后面的属性名写得不规范!在data后面的属性名是不能按照驼峰式的写法,只要把定义的属性名全部换成小写就没有问题了!如下:</p><pre class="brush:bash;toolbar:false"><--HTML写法:-->
<buttonbinTap="buy"data-productid="101"></button>
//JS调用:
buy:function(e){
console.log(e.target.dataset.productid);
//输出结果:101
}</pre><p> 但这种方式有时也会存在 e.target.dataset={},此时productid=undefined,就需要换一种解决办法。。。</p><p> 2)console.log(e)查看</p><p> e对象中包含两个对象分别是currentTarget和target,而真正的数据包含在currentTarget。 打印出e,找到你的数据,通过对象调用的方式即可。</p><p></p><pre class="brush:bash;toolbar:false"><viewclass="section-item-cell"bindtap="wxSortPickerViewItemTap"data-text="{{cell.platformId}}">
<imageclass="logo"mode="{{item.mode}}"src="{{cell.iconUrl}}"></image>
<text>{{cell.platformName}}</text>
<textwx:if="{{cell.status==0}}"style="color:#999;">(系统维护中...)</text>
</view>
</view>
wx.setStorageSync('platId',e.currentTarget.dataset.text);</pre>