當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
JavaScript基础学习--05自定义属性、索引值
生活随笔
收集整理的這篇文章主要介紹了
JavaScript基础学习--05自定义属性、索引值
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
Demos: ??https://github.com/jiangheyan/JavaScriptBase?
?
一、自定義屬性 1、讀寫操作 <input abc="123" type="button" value="按鈕" /> ========================================================= //讀寫: var aBtn = document.getElementsByTagName('input'); aBtn[0].abc = '456'; 2、js可以為任何HTML元素添加任意個自定義屬性 3、自定義屬性可以作為判斷的依據(jù),相對于用class后者flag變量判斷,優(yōu)點: 3.1 ? ? 有時候不允許操作class時,可以利用自定義屬性,通過判斷自定義屬性的值,從而操作流程 3.2 ? ? 一個flag變量只能判斷一組對象,當對象在循環(huán)中有多組對象時,只能用class 或者 自定義屬性 4、for循環(huán)里面的i 1 for(var i = 0; i < aLi.length; i++) { 2 i //這里的 i 是0、1、2…… 3 aLi[i].onclick = function() { 4 i //這里的 i 涉及到閉包和作用域問題,不能返回1、2、…… 只能返回aLi.length 5 } 6 } 5、自定義索引 1 for(var i = 0; i < aLi.length; i++) { 2 aLi[i].index = i; //給每個li添加自定義屬性index,值為i,模擬成為索引 3 aLi[i].onclick = function() { 4 i //這里的 i 涉及到閉包和作用域問題,不能返回1、2、…… 只能返回aLi.length 5 } 6 } 5.1 ? ? 自定義索引的應(yīng)用 1 <!DOCTYPE HTML> 2 <html> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 5 <title>無標題文檔</title> 6 <script> 7 window.onload = function (){ 8 var aBtn = document.getElementsByTagName('input'); 9 var aP = document.getElementsByTagName('p'); 10 11 // 想建立“匹配”“對應(yīng)”關(guān)系,就用索引值 12 var arr = [ '莫濤', '張森', '杜鵬' ]; 13 14 for( var i=0; i<aBtn.length; i++ ){ 15 16 aBtn[i].index = i; // 自定義屬性(索引值) 17 18 aBtn[i].onclick = function (){ 19 // alert( arr[ this.index ] ); 20 this.value = arr[ this.index ]; 21 22 aP[ this.index ].innerHTML = arr[ this.index ]; 23 }; 24 } 25 }; 26 </script> 27 </head> 28 29 <body> 30 31 <input type="button" value="btn1" /> 32 <input type="button" value="btn2" /> 33 <input type="button" value="btn3" /> 34 <p>a</p> 35 <p>b</p> 36 <p>c</p> 37 38 </body> 39 </html>?
轉(zhuǎn)載于:https://www.cnblogs.com/hihao/p/7344630.html
總結(jié)
以上是生活随笔為你收集整理的JavaScript基础学习--05自定义属性、索引值的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 上市公司行情查询站点
- 下一篇: SLF4J with Logback i