DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> JS實現商品篩選功能
JS實現商品篩選功能
編輯:關於JavaScript     

每天一個JS 小demo之商品篩選。主要知識點:DOM方法綜合運用

效果圖:

代碼:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
nav {
height: 50px;
}
nav span {
margin: 0 5px;
}
.show {
color: red;
}
</style>
</head>
<body>
<nav></nav>
<ul>
<li>
<strong>手機:</strong>
<a href="javascript:;">錘子T1</a>
<a href="javascript:;">錘子T2</a>
<a href="javascript:;">堅果U1</a>
<a href="javascript:;">錘子M1</a>
<a href="javascript:;">堅果Pro</a>
</li>
<li>
<strong>價格:</strong>
<a href="javascript:;">3200</a>
<a href="javascript:;">2600</a>
<a href="javascript:;">899</a>
<a href="javascript:;">2799</a>
<a href="javascript:;">2299</a>
</li>
<li>
<strong>屏幕:</strong>
<a href="javascript:;">399</a>
<a href="javascript:;">600</a>
<a href="javascript:;">800</a>
<a href="javascript:;">1200</a>
</li>
</ul>
<script type="text/javascript">
(function(){
var nav = document.querySelector('nav');
var li = document.querySelectorAll('li');
var ids = [];
for(var i = 0; i <li.length; i++){
setClick(li[i],i);
}
function setClick(parent,index){
var option = parent.getElementsByTagName("a");
for(var i = 0; i < option.length; i++){
/*
建一個數組
*/
option[i].onclick = function(){
for(var i = 0; i < option.length; i++){
option[i].className = "";
}
this.className = "show";
var span = ids[index];
if(ids[index]){
span.children[0].innerHTML = this.innerHTML;
return;
}
span = document.createElement("span");
var a = document.createElement("a");
var strong = document.createElement("strong");
a.innerHTML = "x";
a.href="javascript:;";
a.onclick = function(){
nav.removeChild(span);
ids[index]="";
/*
刪除元素清空數組對象位
*/
for(var i = 0; i < option.length; i++){
option[i].className = "";
}
}
strong.innerHTML = this.innerHTML;
span.appendChild(strong);
span.appendChild(a);
ids[index] = span;
/*
元素生成之後,先存入數組的對應位
*/

/*
按照數組的順序重新添加一遍元素
*/
for(var i = 0; i < ids.length; i++){
if(ids[i]){
nav.appendChild(ids[i]);
}
}
};
}
}
})(); 
</script>
</body>
</html>


XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved