[js高手之路] 设计模式系列课程 - DOM迭代器(2)

时间:2022-10-16 20:32:16

如果你对jquery比较熟悉的话,应该用过 eq, first, last, get, prev, next, siblings等过滤器和方法。本文,我们就用迭代设计模式来封装实现,类似的功能

 <!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>
<style>
div,p{
border:1px solid red;
margin:10px;
padding:10px;
}
</style>
<script>
;(function (window, undefined) {
var Iterator = function (el, container) {
var oContainer = container && document.querySelector(container) || document,
aNode = oContainer.querySelectorAll(el),
length = aNode.length,
index = 0,
splice = [].splice;
var isArray = function( obj ){
return Object.prototype.toString.call ( obj ) === '[object Array]';
};
return {
first : function () {
index = 0;
return aNode[index];
},
last : function () {
index = length - 1;
return aNode[index];
},
prev : function () {
if( --index >= 0 ) {
return aNode[index];
}else {
index = 0;
return null;
}
},
next : function () {
if( ++index < length ) {
return aNode[index];
}else {
index = length - 1;
return null;
}
},
get : function ( num ) {
index = num >= length ? length - 1 : num;
(index < 0) && (index = 0);
return aNode[index];
},
eachItem : function ( fn ) {
//G().eachItem( fn, xx, xx, xx );
//args 存储的是 除了第一个参数之外的所有参数
var args = splice.call( arguments, 1 );
for( var i = 0; i < length; i++ ){
fn.apply( aNode[i], args );
}
},
dealItem : function( n, fn ){
fn.apply( this.get( n ), splice.call( arguments, 2 ) );
},
exclusive : function( num, aFn, curFn ){
this.eachItem( aFn );
if( isArray( num ) ) {
for( var i = 0, len = num.length; i < len; i++ ){
this.dealItem( num[i], curFn );
}
}else {
this.dealItem( num, curFn );
}
}
};
};
window.Iterator = Iterator;
})(window, undefined);
window.onload = function(){
var oIter = Iterator( 'p', '#box' );
// var oNode = oIter.first(); // var oNode = oIter.get(2);
// oNode.style.backgroundColor = 'green';
// oNode = oIter.prev();
// oNode.style.backgroundColor = 'green';
// oNode = oIter.prev();
// oNode = oIter.next();
// oNode.style.backgroundColor = 'orange'; // oIter.eachItem(function( c, s ){
// this.innerHTML = c;
// this.style.color = s;
// }, '跟ghostwu学习设计模式', 'red' ); // oIter.dealItem( 0, function( c, s ){
// console.log( c, s );
// this.innerHTML = c;
// this.style.color = s;
// }, '跟着ghostwu学习设计模式', 'red' ); oIter.exclusive( [2,3], function(){
this.innerHTML = '跟着ghostwu学习设计模式';
this.style.color = 'red';
}, function(){
this.innerHTML = '跟着ghostwu学习设计模式';
this.style.color = 'green';
} ); }
</script>
</head>
<body>
<div id="box">
<p>this is a test string</p>
<p>this is a test string</p>
<p>this is a test string</p>
<p>this is a test string</p>
<p>this is a test string</p>
</div>
<p>this is a test string</p>
<p>this is a test string</p>
</body>
</html>