原生JS实现多条件筛选

时间:2022-06-05 04:54:05

本文实例为大家分享了原生JS实现多条件筛选的具体代码,供大家参考,具体内容如下

我在学JS初始看到的教程基本都是JS二级联动查询、三级联动查询;如下图:

原生JS实现多条件筛选

但有时并不需要级联查询,如购买商品时:

原生JS实现多条件筛选

今天我以慕课网前端样式作为参考做了下面的Demo,基于原生JS

  1. <div id="direction">
  2. <strong>方向:</strong>
  3. <span class="active">全部</span>
  4. <span>前端</span>
  5. <span>后台</span>
  6. <span>数据库</span>
  7. <span>UI设计</span>
  8. </div>
  9. <div id="category">
  10. <strong>分类:</strong>
  11. <span class="active">全部</span>
  12. <span>HTML/CSS</span>
  13. <span>JavaScript</span>
  14. <span>jQuery</span>
  15. <span>Python</span>
  16. <span>Java</span>
  17. <span>AngularJS</span>
  18. </div>
  19. <div id="type">
  20. <strong>类型:</strong>
  21. <span class="active">全部</span>
  22. <span>基础</span>
  23. <span>案例</span>
  24. <span>框架</span>
  25. <span>工具</span>
  26. </div>
  27. <strong>返回值:</strong>
  28. <p id="Res"></p>
  1. <style>
  2. span{display: inline-block;
  3. cursor: pointer; padding: 8px; border: 1px solid #999;}
  4. span.active{
  5. background-color: #c14d00;
  6. }
  7. </style>
  1. <script>
  2. var dSpan = document.getElementById('direction').getElementsByTagName('span');
  3. var cSpan = document.getElementById('category').getElementsByTagName('span');
  4. var tSpan = document.getElementById('type').getElementsByTagName('span');
  5. var aSpan = document.getElementsByTagName('span');
  6. var oDirection = document.getElementById('direction');
  7. var oCategory = document.getElementById('category');
  8. var oType = document.getElementById('type');
  9. var oRes = document.getElementById('Res');
  10. dSpan[0].className = 'active';
  11. cSpan[0].className = 'active';
  12. tSpan[0].className = 'active';
  13. for(var i=0; i<aSpan.length; i++){
  14. aSpan[i].onclick = function(){
  15. var siblings = this.parentNode.children;
  16. for(var j=0; j<siblings.length; j++){
  17. siblings[j].className = '';
  18. }
  19. this.className = 'active';
  20. if(this.parentNode == oDirection || this.parentNode == oCategory || this.parentNode == oType){
  21. returnRes();
  22. }
  23. }
  24. }
  25.  
  26. function returnRes(){
  27. var o1 = 0, o2 = 0, o3 = 0;
  28. for(var i=0; i<dSpan.length; i++){
  29. if(dSpan[i].className == 'active'){
  30. o1 = i;
  31. }
  32. }
  33. for(var i=0; i<cSpan.length; i++){
  34. if(cSpan[i].className == 'active'){
  35. o2 = i;
  36. }
  37. }
  38. for(var i=0; i<tSpan.length; i++){
  39. if(tSpan[i].className == 'active'){
  40. o3 = i;
  41. }
  42. }
  43. oRes.innerHTML = (dSpan[o1].innerHTML + "," + cSpan[o2].innerHTML + "," + tSpan[o3].innerHTML);
  44. }
  45. </script>

最后附上效果图:

原生JS实现多条件筛选

注:本篇博文是 【无条件】的分类筛选

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

原文链接:https://blog.csdn.net/u013451157/article/details/78507008