jQuery中的函数封装

    科技2022-07-17  126

    1.函数封装的概念: 函数是由事件驱动的或者当它被调用时执行的可重复使用的代码块。 用函数把重复的代码块包裹起来就是函数封装。

    2.封装的作用: 其实就是为了减少代码的冗余,增加代码的可读性与易维护性, 将实现同一功能的代码封装起来,在需要实现这一功能时调用即可。

    举例1 删除dom对象的空白节点: function removeNode(nodee) { for (var i = 0; i < nodee.length; i ++) { if (nodee[i].nodeType === 3 && /^\s+$/.test(nodee[i].nodeValue)) { nodee[i].parentNode.removeChild(nodee[i]); } } return nodee; }

    举例2 阻止默认行为: function stopcancelable(evt){ var e=evt||window.event; if(e.preventDefault()){ e.preventDefault(); }else{ cancelable=true } }

    举例2 随机数: function random(min,max){ return parseInt(Math.random()*(max-min))+min; }

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> *{ margin: 0; padding: 0; } #warp1{ width: 300px; height: 330px; border: 1px solid red; position: relative; margin: 0 auto; } #warp2{ width: 300px; height: 330px; border: 1px solid red; position: relative; margin: 0 auto; } button{ width: 100px; height: 30px; border: 0; float: left; } #box1{ width:100% ; height: 300px; background: red; color: #fff; font-size: 100px; position: absolute; top:30px; display: block; } #box2{ width:100% ; height: 300px; background: yellow; color: #fff; font-size: 100px; position: absolute; top:30px; } #box3{ width:100% ; height: 300px; background: blue; color: #fff; font-size: 100px; position: absolute; top:30px; } .box{ display: none; } </style> </head> <body> <div id="warp1"> <button>1</button> <button>2</button> <button>3</button> <div id="box1" class="box">1</div> <div id="box2" class="box">2</div> <div id="box3" class="box">3</div> </div> <div id="warp2"> <button>1</button> <button>2</button> <button>3</button> <div id="box1" class="box">1</div> <div id="box2" class="box">2</div> <div id="box3" class="box">3</div> </div> </body> <script type="text/javascript"> var obox1=document.getElementById('warp1'); var obtn1=obox1.getElementsByTagName('button'); var odiv1=obox1.getElementsByClassName('box'); var obox2=document.getElementById('warp2'); var obtn2=obox2.getElementsByTagName('button'); var odiv2=obox2.getElementsByClassName('box'); for(var i=0;i<obtn1.length; i++){ obtn1[i].index=i; obtn1[i].onclick=function(){ for(var j=0; j<odiv1.length; j++){ odiv1[j].style.display='none'; } odiv1[this.index].style.display='block'; } } for(var i=0;i<obtn2.length; i++){ obtn2[i].index=i; obtn2[i].onclick=function(){ for(var j=0; j<odiv2.length; j++){ odiv2[j].style.display='none'; } odiv2[this.index].style.display='block'; } } </script> </html>
    Processed: 0.010, SQL: 8