小程序如何获取子元素

小程序如何获取子元素.jpg" alt="小程序如何获取子元素">

1、使用setData方法更新数据

小程序中,可以使用setData方法来更新Page实例中的数据。为了获取子元素,需要通过组件的id属性或data-*自定义属性来定位子元素。例如:

Page({
  data: {
    list:[
      {id: 0, name: 'apple'},
      {id: 1, name: 'banana'},
      {id: 2, name: 'orange'}
    ]
  },
  onItemClick(event) {
    const id = event.currentTarget.dataset.id
    // 通过id定位父级元素,在父级元素中查找子元素
    const index = this.data.list.findIndex(item => item.id === id)
    console.log(index)
  }
})

2、使用this.selectComponent方法获取组件实例

在小程序中,可以使用this.selectComponent方法来获取组件实例。为了获取子元素,需要假设你的组件已经编写完毕,并且给某个需要获取子元素的组件设置了

Component({
  properties: {},
  methods: {},
  ready() {
    // 获取子元素
    const child = this.selectComponent('.child')
    console.log(child.data)
  }
})

3、使用wx.createSelectorQuery方法获取DOM节点信息

在小程序中,可以使用wx.createSelectorQuery方法来获取 DOM 节点信息。为了获取子元素,需要将节点取到之后再进行查找,例如:

Page({
  onShow() {
    // 获取父级元素
    const query = wx.createSelectorQuery()
    query.select('.parent').boundingClientRect()
    query.exec(res => {
      const parentRect = res[0]
      // 获取所有子元素的信息
      const childNodes = [...parent.childNodes]
      childNodes.forEach((node, index) => {
        const { top, left, width, height } = node.getBoundingClientRect()
        console.log('child' + index + 'of parent: ', top, left, width, height)
      })
    })
  }
})

4、总结

以上是三种获取小程序子元素的方法。具体的实现方式根据需求来选择,推荐使用setData方法和this.selectComponent方法,如果需要获取DOM节点,则使用wx.createSelectorQuery方法。

本文由科技提供