js的一些实用技巧
1 setTimeout(function(i, j){ 2 console.log(i); // 111 3 console.log(j); // 222 4 }, 1000, 111, 222); 5 6 setInterval(function(i, j){ 7 console.log(i); // 111 8 console.log(j); // 222 9 }, 1000, 111, 222);
1 var sHtml = 2 ‘<div class="article">3 <div class="head">标题</div>4 <div class="con">内容</div>5 </div>‘;
1 var aNum = [1, 2, 3]; 2 console.log(typeof aNum); // object 3 console.log(typeof(aNum)); // object 4 5 console.log(aNum instanceof Array); // true 6 console.log(aNum instanceof(Array)); // true 7 8 console.log(aNum in window); // false 9 console.log(aNum in(window)); // false
1 var i = 0; 2 for(;;){ 3 if(i == 4)break; 4 console.log(i++); // 0, 1, 2, 3 5 }
1 var name = ‘hum‘; 2 function Test(name){ 3 this.name = name; 4 }; 5 Test.prototype.getName = function() { 6 console.log(this.name); 7 }; 8 9 var oTest = new Test(‘jolin‘); 10 oTest.getName(); // jolin 11 oTest.getName.call(); // hum 12 oTest.getName.call(null); // hum
1 <button>添加</button> 2 <ul></ul> 3 <script> 4 window.onload = function(){ 5 var oUl = document.getElementsByTagName(‘ul‘)[0], 6 aLi = document.getElementsByTagName(‘li‘), 7 oBtn = document.getElementsByTagName(‘button‘)[0], 8 iNum = 0; 9 10 oBtn.onclick = function(){ 11 var oLi = document.createElement(‘li‘); 12 oLi.innerHTML = ++iNum; 13 oUl.insertBefore(oLi, aLi[0]); // 第一次添加也会成功 14 }; 15 }; 16 </script>
1 <button>添加</button> 2 <button>移除</button> 3 <ul></ul> 4 <script> 5 window.onload = function(){ 6 var oUl = document.getElementsByTagName(‘ul‘)[0], 7 aLi = document.getElementsByTagName(‘li‘), 8 oBtn0 = document.getElementsByTagName(‘button‘)[0], 9 oBtn1 = document.getElementsByTagName(‘button‘)[1], 10 iNum = 0; 11 console.log(aLi.length); // 0 12 oBtn0.onclick = function(){ 13 var oLi = document.createElement(‘li‘); 14 oLi.innerHTML = ++iNum; 15 oUl.insertBefore(oLi, aLi[0]); 16 console.log(aLi.length); 17 }; 18 oBtn1.onclick = function(){ 19 if(aLi.length) { // 必须判断否则removeChild会报错 20 oUl.removeChild(aLi[0]); 21 } 22 console.log(aLi.length); 23 }; 24 }; 25 </script>
1 // 常用 2 (function () { 3 console.log(‘function‘); 4 })(); 5 6 // 特殊 7 !function(){ 8 console.log(‘function‘); 9 }(); 10 +function(){ 11 console.log(‘function‘); 12 }(); 13 -function(){ 14 console.log(‘function‘); 15 }();
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。