d3过滤
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>过滤</title> 6 <script src="d3.js"></script> 7 </head> 8 <style> 9 .h-bar { 10 min-height: 15px; 11 min-width: 10px; 12 background-color: steelblue; 13 margin-bottom: 2px; 14 font-size: 11px; 15 color: #f0f8ff; 16 text-align: right; 17 padding-right: 2px; 18 } 19 .selected{ 20 background-color: pink; 21 } 22 </style> 23 24 <body> 25 <script> 26 // 定义数据 27 let data = [ 28 { expense: 10, category: "Retail" }, 29 { expense: 15, category: "Gas" }, 30 { expense: 30, category: "Retail" }, 31 { expense: 50, category: "Dining" }, 32 { expense: 80, category: "Gas" }, 33 { expense: 65, category: "Retail" }, 34 { expense: 55, category: "Gas" }, 35 { expense: 30, category: "Dining" }, 36 { expense: 20, category: "Retail" }, 37 { expense: 10, category: "Dining" }, 38 { expense: 8, category: "Gas" } 39 ] 40 function render(data, category) { 41 // 进入 42 d3.select("body").selectAll('div.h-bar') 43 .data(data) 44 .enter() 45 .append("div") 46 .attr('class', 'h-bar') 47 .append('span') 48 // 退出 49 d3.select("body").selectAll('div.h-bar') 50 .data(data) 51 .exit() 52 .remove() 53 // 更新 54 d3.select("body").selectAll('div.h-bar') 55 .data(data) 56 .attr("class", "h-bar") //为了初始化下样式 57 .style('width', function(d) { 58 return (d.expense*5) + 'px' 59 }) 60 .select("span") 61 .text(function(d) { 62 return d.category; 63 }); 64 65 d3.select("body").selectAll('div.h-bar') 66 .filter(function(d, i) { 67 return d.category == category 68 }) 69 .classed("selected", true) 70 } 71 72 render(data); 73 function select(category){ 74 render(data, category); 75 } 76 </script> 77 <div> 78 <button onclick="select('Retail')">Retail</button> 79 <button onclick="select('Gas')">Gas</button> 80 <button onclick="select('Dining')">Dining</button> 81 <button onclick="select()">Clear</button> 82 </div> 83 </body> 84 85 </html>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!