2012-03-10 57 views
2

非常感謝任何回覆。Jquery從頭開始手風琴:手風琴和Jquery性能標記Q

我正在寫一個jQuery的手風琴,但是不知道我的標記和jQuery是正確的或不..(與語義HTML保持)

我的第一個問題是什麼是在accourdion正確的語義化的HTML我正在使用它的上下文(JSFIDDLE example)..目前我使用ul ...與李和一個div的內容..

第二個問題,可以改善這個jquery,並在那裏衡量一個特定的jQuery腳本的性能?

JSFIDDLE example

$(document).ready(function(){ 
    //store the exact block of html we are working with... the context 
    var $context = $("ul#accordion")[0]; 
    console.log($context); 
    //check the context 
    $("li a", $context).live("click", function(e){ 
     //store this due to being used more than once 
     var $clicked = $(this); 
     //slide anything up thats already open 
     $("li div", $context).slideUp(200); 
     //test to see if the div is hidden or not.. 
     //slide down if hidden 
     if($clicked.next().is(":hidden")){ 
      $clicked.next().slideDown(200); 
     }; 
    //prevent default behaviour 
    e.preventDefault(); 
    }); 

});​ 
+0

兩個看起來好像沒什麼問題。爲了您的興趣,您可能想要與jQuery UI的源代碼示例進行比較:http://jqueryui.com/demos/accordion/ – Smamatti 2012-03-10 22:30:15

+0

偉大的建議,謝謝! – Iamsamstimpson 2012-03-10 22:32:20

+1

我會做'$ clicked.next(':hidden')。slideDown(200);'而不是'if(...)'。另外,由於一個id必須是唯一的,所以'$ context'可以省略'[0]'。 '$ clicked'只使用一次,所以我建議刪除它,並直接使用'$(「li div」,this)'。 – 2012-03-10 22:33:33

回答

1
  • 由於您使用$(selector, context)(等於$(context).find(selector)),只有一個元素上,我建議將它們合併:$('ul#accordion li')
  • 使用$(ancestor).on('event', 'selector', fn)代替$('ancestor selector').live(fn)
  • 廣場e.preventDefault()在上面。只要你的代碼發生錯誤,消極的副作用就不會發生。
  • 我的其他建議更改已在您的問題的評論中提出。

代碼:

$(document).ready(function(){ 
    // :first can be omitted, but it's an literal translation 
    $("ul#accordion:first li").on("click", "a", function(e) { 
     // prevent default behaviour 
     e.preventDefault(); 

     // slide anything up thats already open 
     $("li div", this).slideUp(200); 

     // slide down if hidden 
     $clicked.next(':hidden').slideDown(200); 
    }); 
}); 
+0

謝謝rob這是我正在尋找的答案的確切類型,非常感謝。 – Iamsamstimpson 2012-03-10 22:56:34