> 文章列表 > 【微信小程序】selectComponent(#id)失败得到是null分析

【微信小程序】selectComponent(#id)失败得到是null分析

【微信小程序】selectComponent(#id)失败得到是null分析

小程序中无法像网页中轻易的获取DOM元素,需要依靠

  • this.selectComponent(#id)
  • this.selectAllComponents(#id)

本文主要针对 this.selectComponent 获取DOM元素失败的原因

下面开始正文

【微信小程序】selectComponent(#id)失败得到是null分析
上图为我的业务代码,由图可知,通过for循环遍历渲染card自定义组件,每个组件的id都为666

【微信小程序】selectComponent(#id)失败得到是null分析
这里获取一下DOM元素并打印,打印结果看下图

【微信小程序】selectComponent(#id)失败得到是null分析
显然,失败了,得到的DOM元素是null,我们并没有获取到想要的DOM元素

现在我们更改一下,将id改为 d666,即不要数字开头

【微信小程序】selectComponent(#id)失败得到是null分析【微信小程序】selectComponent(#id)失败得到是null分析

【微信小程序】selectComponent(#id)失败得到是null分析获取成功了

显然,id不可以数字开头,一个很细小的点,官方文档没有写,容易踩坑~特此记录