js基础 ---- 事件委托的实战
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>地图栏</title> </head> <body> <!-- 为 ECharts 准备一个具备大小(宽高)的 DOM --> <div id="main" style="width: 600px;height:400px;"></div> <div style="display: flex;" id='iptBox'> 美国:<input id="countryA" value=10 /> 日本: <input id="countryJ" value=14 /> 中国: <input id="countryC" value=18 /> 德国: <input id="countryD" value=12 /> </div> </body> <script src="https://cdn.bootcdn.net/ajax/libs/echarts/5.0.1/echarts.common.js"></script> <script> var myChart = echarts.init(document.getElementById('main')); var AGDP = document.getElementById('countryA').value; var JGDP = document.getElementById('countryJ').value; var CGDP = document.getElementById('countryC').value; var DGDP = document.getElementById('countryD').value; var arrGDP = [AGDP, JGDP, CGDP, DGDP]; var iptBox = document.getElementById('iptBox'); var option = { title: { text: '面试题1' }, tooltip: { }, legend: { data: ['GDP'] }, xAxis: {}, yAxis: { data: ['美国', '日本', '中国', '德国'] }, series: [{ name: 'GDP', type: 'bar', data: arrGDP }] } myChart.setOption(option, true) //通过事件委托来修input的value值 减少DOM操作来优化性能 iptBox.addEventListener('change', (e) => { let ev = e || window.event; console.log(ev.target.id == 'countryA') let elId = ev.target.id switch (elId) { case 'countryA': arrGDP[0] = ev.target.value break; case 'countryJ': arrGDP[1] = ev.target.value break; case 'countryC': arrGDP[2] = ev.target.value break; case 'countryD': arrGDP[3] = ev.target.value break; } option.series[0].data = arrGDP myChart.setOption(option, true) }) </script> </html>