使用e.target.dataset的问题

<p>在微信开发中我们经常会用到标签中属性的属性值,有时候我们通过 data-* 和 e.target.dateset 来获取属性值会出现一点小bug,即是调用出来的数据是undefined。</p><p>  1)方案1–去掉驼峰式命名,纯小写</p><pre class="brush:bash;toolbar:false">&lt;--HTML写法:--&gt; &lt;buttonbinTap=&quot;buy&quot;data-textId=&quot;101&quot;&gt;&lt;/button&gt; //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">&lt;--HTML写法:--&gt; &lt;buttonbinTap=&quot;buy&quot;data-productid=&quot;101&quot;&gt;&lt;/button&gt; //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">&lt;viewclass=&quot;section-item-cell&quot;bindtap=&quot;wxSortPickerViewItemTap&quot;data-text=&quot;{{cell.platformId}}&quot;&gt; &lt;imageclass=&quot;logo&quot;mode=&quot;{{item.mode}}&quot;src=&quot;{{cell.iconUrl}}&quot;&gt;&lt;/image&gt; &lt;text&gt;{{cell.platformName}}&lt;/text&gt; &lt;textwx:if=&quot;{{cell.status==0}}&quot;style=&quot;color:#999;&quot;&gt;(系统维护中...)&lt;/text&gt; &lt;/view&gt; &lt;/view&gt; wx.setStorageSync(&#39;platId&#39;,e.currentTarget.dataset.text);</pre>

按月统计

  1. 2021-12 (18)
  2. 2022-02 (2)
  3. 2022-03 (2)
  4. 2023-05 (1)
返回顶部 留言