非常感谢您的回复。
我正在写一个jquery手风琴,但不知道我的标记和jquery是否正确。。(与语义html一致)
我的第一个问题是,在我使用它的上下文中,什么是正确的语义html(JSFIDDLE示例)。。目前我使用一个ul。。。内容为li和div。。
第二个问题,这个jquery可以改进吗?是否可以衡量特定jquery脚本的性能?
JSFIDDLE示例
$(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();
});
});
- 由于您只在一个元素上使用
$(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);
});
});