前两天做项目需要动态添加echarts,可把我难住了,问了好多人终于解决,今天分享一下
html
<!-- 点击的按钮 -->
<div class="btn">点击</div>
<!-- 需要添加echarts的盒子 -->
<div class="cont"></div>
css
.cont{
width: 500px;
height: 500px;
border: 1px solid blue;
}
.box{
width: 200px;
height: 200px;
border: 1px solid red;
margin: 10px 0;
}
echarts.js
function echar(){
var arr = Array.from(document.querySelectorAll(".c1"));
var charArr = arr.map(item=>echarts.init(item))
// 配置数据
var option1 = {
title: {
text: 'ECharts 入门示例'
},
tooltip: {},
xAxis: {
data: ["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"]
},
yAxis: {},
series: [{
name: '销量',
type: 'bar',
data: [5, 20, 36, 10, 10, 20]
}]
};
// 渲染图表
charArr.forEach(item=>item.setOption(option1))
}
点击插入的js
$(function(){
$('.btn').click(function(){
$('.cont').append('<div class="box"></div>')
var c1 = $('.box').children('.c1');
console.log(c1.length);
if(c1.length == 0){
$('.box').append('<div class="c1" style="width:100%;height:100%;"></div>')
}else if(c1.length>0){
$('.box').append('<div class="c1" style="width:100%;height:100%;"></div>')
for(var i=0;i<c1.length;i++){
$('.box .c1:eq('+i+')').remove();
}
}
echar();
})
})
完整的demo
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>echarts</title>
<style>
.cont{
width: 500px;
height: 500px;
border: 1px solid blue;
}
.box{
width: 200px;
height: 200px;
border: 1px solid red;
margin: 10px 0;
}
</style>
<link rel="stylesheet" href="css/jquery-ui.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="btn">点击</div>
<div class="cont"></div>
</div>
</body>
<script src="js/jquery.min.js"></script>
<script src="js/echarts.min.js"></script>
<script src="js/jquery-ui.js"></script>
<script>
$(function(){
$('.btn').click(function(){
$('.cont').append('<div class="box"></div>')
var c1 = $('.box').children('.c1');
console.log(c1.length);
if(c1.length == 0){
$('.box').append('<div class="c1" style="width:100%;height:100%;"></div>')
}else if(c1.length>0){
$('.box').append('<div class="c1" style="width:100%;height:100%;"></div>')
for(var i=0;i<c1.length;i++){
$('.box .c1:eq('+i+')').remove();
}
}
echar();
})
})
function echar(){
var arr = Array.from(document.querySelectorAll(".c1"));
var charArr = arr.map(item=>echarts.init(item))
// 配置数据
var option1 = {
title: {
text: 'ECharts 入门示例'
},
tooltip: {},
xAxis: {
data: ["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"]
},
yAxis: {},
series: [{
name: '销量',
type: 'bar',
data: [5, 20, 36, 10, 10, 20]
}]
};
// 渲染图表
charArr.forEach(item=>item.setOption(option1))
}
</script>
</html>
最终效果