<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <script src="js/jquery-3.2.1.min.js"></script> <style> .active{ color: red; } </style> </head> <body> <ul class="list"> <li><button>上海</button></li> <li><button>天津</button></li> <li><button>广州</button></li> <li><button>北京</button></li> <li><button>深圳</button></li> </ul> <div class="container"></div> <script> $(function () { let arr=[]; $('.list li button').click(function () { let text=$(this).text(); let ind=arr.indexOf(text); if(ind===-1){ arr.push(text); $(this).addClass('active'); $('.container').append($('<span>'+text+'</span>')) }else { arr.splice(ind,1); $(this).removeClass('active'); let children=$('.container').children(); children[ind].remove(); } }) }) </script> </body> </html>
点击添加样式并添加到数组中,再次点击取消样式并从数组中移除
最新推荐文章于 2022-12-12 11:10:29 发布