我們先說(shuō)一下第一種方法,(此方法為一位QQ好友提供,感謝此人,此人昵稱(chēng)是:exf)
<body> <ul>Title1 <li>11111</li> </ul> <ul>Title2 <li>22222</li> </ul> <ul>Title3 <li>33333</li> </ul> <ul>Title4 <li>44444</li> </ul> <script type='text/javascript'> ul=$$('ul'); ul.addEvent('click',function(){ alert(ul.indexOf(this)); }); </script>
其實(shí)除了上邊的方法外還有一種方法也能得到索引值,看下邊的例子:
<body> <ul>Title1 <li>11111</li> </ul> <ul>Title2 <li>22222</li> </ul> <ul>Title3 <li>33333</li> </ul> <ul>Title4 <li>44444</li> </ul> <script type='text/javascript'> ul=$$('ul'); ul.each(function($I,i){ $I.onclick=function(){ alert(i); }; }) </script>
兩種方法孰優(yōu)孰劣一看便知,第一種方法需要再次使用indexOf函數(shù)判斷,而第二種方式直接是作為參數(shù)把索引值傳遞進(jìn)去了,就不需要額外的計(jì)算了.因此如果您需要獲取索引值得時(shí)候推薦使用第二種方法.
下邊我寫(xiě)了一個(gè)手風(fēng)琴插件用來(lái)演示兩種方法在實(shí)際應(yīng)用過(guò)程中的表現(xiàn).
<style type="text/css"> ul,li{font-size:12px;font-family:arial;padding:0;margin:0;} ul{width:300px;line-height:24px;font-weight:bold;background-color:#C1C2C1;border-bottom:1px solid #fff;text-indent:10px;} li{list-style:none;font-weight:normal;background-color:#e1e1e1;} </style> </head> <body> <ul>Title1 <li>11111</li> </ul> <ul>Title2 <li>22222</li> </ul> <ul>Title3 <li>33333</li> </ul> <ul>Title4 <li>44444</li> </ul> <script type='text/javascript'> var Acc=new Class({ Implements:[Options,Events], options:{ $Boxtit:false }, initialize:function(options){//初始化構(gòu)造函數(shù) this.setOptions(options);//設(shè)置options if(!this.options.$Boxtit){return false;} this.Core(); }, Core:function(){ $Boxtit=this.options.$Boxtit; $Boxmsg=$Boxtit.getElement('li'); $Boxmsg.setStyle("display","none"); $Boxtit.each(function($I,i1){ $I.onclick=function(){ //i2=$Boxtit.indexOf(this);console.log(i1+'|'+i2);//這裡的i1和i2實(shí)際上都是索引值 $Boxmsg.setStyle("display","none"); this.getElement('li').setStyle("display",""); }; }) } }); new Acc({$Boxtit:$$('ul')}); </script>
只不過(guò)在上邊的插件中為了提高效率,因此我使用了this,這樣比用索引找尋DOM效率更高一些.