用Mootools獲得操作索引的兩種方法分享

來源:互聯網
上載者:User

我們先說一下第一種方法,(此方法為一位QQ好友提供,感謝此人,此人暱稱是: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>

其實除了上邊的方法外還有一種方法也能得到索引值,看下邊的例子:
複製代碼 代碼如下:
<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>

  兩種方法孰優孰劣一看便知,第一種方法需要再次使用indexOf函數判斷,而第二種方式直接是作為參數把索引值傳遞進去了,就不需要額外的計算了.因此如果您需要擷取索引值得時候推薦使用第二種方法.
  下邊我寫了一個手風琴外掛程式用來示範兩種方法在實際應用過程中的表現.
複製代碼 代碼如下:
<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){//初始化建構函式
    this.setOptions(options);//設置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實際上都是索引值
          $Boxmsg.setStyle("display","none");
          this.getElement('li').setStyle("display","");
        };
    })
  }
});
new Acc({$Boxtit:$$('ul')});
</script>

只不過在上邊的外掛程式中為了提高效率,因此我使用了this,這樣比用索引找尋DOM效率更高一些.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.