亲宝软件园·资讯

展开

JS多条件筛选 原生JS实现多条件筛选

abloume 人气:2
想了解原生JS实现多条件筛选的相关内容吗,abloume在本文为您仔细讲解JS多条件筛选的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:js多条件筛选,js条件筛选,js筛选,下面大家一起来学习吧。

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

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

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

<div id="direction">
 <strong>方向:</strong>
 <span class="active">全部</span>
 <span>前端</span>
 <span>后台</span>
 <span>数据库</span>
 <span>UI设计</span>
</div>
<div id="category">
 <strong>分类:</strong>
 <span class="active">全部</span>
 <span>HTML/CSS</span>
 <span>JavaScript</span>
 <span>jQuery</span>
 <span>Python</span>
 <span>Java</span>
 <span>AngularJS</span>
</div>
<div id="type">
 <strong>类型:</strong>
 <span class="active">全部</span>
 <span>基础</span>
 <span>案例</span>
 <span>框架</span>
 <span>工具</span>
</div>
<strong>返回值:</strong>
<p id="Res"></p>
<style>
 span{display: inline-block;
  cursor: pointer; padding: 8px; border: 1px solid #999;}
 span.active{
  background-color: #c14d00;
 }
</style>
<script>
 var dSpan = document.getElementById('direction').getElementsByTagName('span');
 var cSpan = document.getElementById('category').getElementsByTagName('span');
 var tSpan = document.getElementById('type').getElementsByTagName('span');
 var aSpan = document.getElementsByTagName('span');
 var oDirection = document.getElementById('direction');
 var oCategory = document.getElementById('category');
 var oType = document.getElementById('type');
 var oRes = document.getElementById('Res');
 dSpan[0].className = 'active';
 cSpan[0].className = 'active';
 tSpan[0].className = 'active';
 for(var i=0; i<aSpan.length; i++){
  aSpan[i].onclick = function(){
   var siblings = this.parentNode.children;
   for(var j=0; j<siblings.length; j++){
    siblings[j].className = '';
   }
   this.className = 'active';
   if(this.parentNode == oDirection || this.parentNode == oCategory || this.parentNode == oType){
    returnRes();
   }
  }
 }

 function returnRes(){
  var o1 = 0, o2 = 0, o3 = 0;
  for(var i=0; i<dSpan.length; i++){
   if(dSpan[i].className == 'active'){
    o1 = i;
   }
  }
  for(var i=0; i<cSpan.length; i++){
   if(cSpan[i].className == 'active'){
    o2 = i;
   }
  }
  for(var i=0; i<tSpan.length; i++){
   if(tSpan[i].className == 'active'){
    o3 = i;
   }
  }
  oRes.innerHTML = (dSpan[o1].innerHTML + "," + cSpan[o2].innerHTML + "," + tSpan[o3].innerHTML);
 }
</script>

最后附上效果图:

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

加载全部内容

相关教程
猜你喜欢
用户评论