数组each遍历渲染如何给第一个div添加class
并且在点击每个div的时候,有被选中的效果
其他div背景颜色移除
被点击的div背景颜色添加。
<!DOCTYPE HTML> <html xmlns:th="http://www.thymeleaf.org"> <head> <title></title> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link rel="stylesheet" href="https://cdn.bootcss.com/twitter-bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script> <script src="https://cdn.bootcss.com/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script> <style> /* 楼层条样式 */ .floorBar { position: absolute; right: 30%; top: 10%; color: #fff; z-index: 1000; width: 29px; height: 150px; text-align: center; box-shadow: 0px 0px 10px #0076ff inset; cursor: pointer; overflow: auto; background: rgba(39, 32, 97, 0.5); font-size: 12px; } .floorinside { line-height: 31px; height: 30px; } .on { background:#337ab7; color:#fff } </style> </head> <body> <div class="floorBar"></div> </body> <script type="text/javascript"> $.ajax({ url: "test.json", data: {}, type: "GET", success: function(data) { var html = ""; $.each(data.paramValue.split(','), function(i, item) { html += '<div onclick="updata2dTile()" class="floorinside">F' + item + '</div>'; }); $(".floorBar").html(html); $(".floorinside:eq(0)").addClass('on'); $(".floorinside").click(function() { $(this).addClass("on").siblings().removeClass("on"); }); }, error: function(err) { console.log(err); } }) //点击事件 /* function updata2dTile(item) { $(this).addClass("on").siblings().removeClass("on"); } */ </script> </html>
json
{ "paramValue": "00,01,02,03,04" }