echarts使用getElementById正常,但是使用uniapp发布到微信小程序,利用微信开发者工具查看时报错
在uniapp
中使用getElementById
有时会在微信小程序中出现错误,因为小程序中没有getElementById
这个方法。
相反,小程序中使用uni.createSelectorQuery
API 取代 getElementById
方法。您可以尝试使用以下代码作为替代方案:
// 获取canvas元素的节点信息
uni.createSelectorQuery().select('#myCanvas').node(res => {
// 获取canvas节点尺寸
const canvas = res.node;
// 初始化echarts
const myChart = echarts.init(canvas, null, {renderer: 'canvas'});
// 设置options参数
myChart.setOption({...});
});
在上面的代码中,使用uni.createSelectorQuery().select('#myCanvas')
获取canvas
元素的节点信息,并通过回调函数获取canvas
节点尺寸,并将其作为第一个参数传递给echarts.init
方法。
通过这种方式,您应该可以避免在微信小程序中遇到getElementById
方法错误的问题。