Dan*_*anC 0 performance jquery jquery-1.3
我有以下jQuery语句工作正常但我想知道它是否可以缩短,如果使它更简洁将加快性能或不?
奇怪的起始标签的原因是它是一个wordpress主题.
提前干杯!
jQuery(document).ready(function($) {
$(".sidebar ol#navigation li.work a").click(function() {
$("#content #second_nav").toggle("fast");
$("#content #second_nav ul.options_3").css('display','none');
$("#content #second_nav ul.options_2").css('display','none');
$("#content #second_nav ul.options_4").css('display','none');
$('.active_2').removeClass('active_2');
$('.active').removeClass('active');
$(this).toggleClass('selected');
});
$("#content #second_nav ul.options li a#work").click(function() {
$('.active').removeClass('active');
$(this).attr('class','active');
$("#content #second_nav ul.options_2").toggle("fast");
$("#content #second_nav ul.options_4").css('display','none');
$("#content #second_nav ul.options_3").css('display','none');
});
$("#content #second_nav ul.options li a#writing").click(function() {
$('.active').removeClass('active');
$(this).attr('class','active');
$("#content #second_nav ul.options_4").toggle("fast");
$("#content #second_nav ul.options_3").css('display','none');
$("#content #second_nav ul.options_2").css('display','none');
$('.active_2').removeClass('active_2');
});
$("#content #second_nav ul.options_2 li a#collage").click(function() {
$('.active_2').removeClass('active_2');
$('ul.options_3').css('display','none');
$(this).attr('class','active_2');
$("#content #second_nav ul.options_3#collage").toggle("fast");
});
$("#content #second_nav ul.options_2 li a#painting").click(function() {
$('.active_2').removeClass('active_2');
$('ul.options_3').css('display','none');
$(this).attr('class','active_2');
$("#content #second_nav ul.options_3#painting").toggle("fast");
});
$("#content #second_nav ul.options_2 li a#print").click(function() {
$('.active_2').removeClass('active_2');
$('ul.options_3').css('display','none');
$(this).attr('class','active_2');
$("#content #second_nav ul.options_3#print").toggle("fast");
});
$("#content #second_nav ul.options_2 li a#photo").click(function() {
$('.active_2').removeClass('active_2');
$('ul.options_3').css('display','none');
$(this).attr('class','active_2');
$("#content #second_nav ul.options_3#photo").toggle("fast");
});
});
Run Code Online (Sandbox Code Playgroud)
为了性能:
这是最好用的ID和类以尽可能少的节点选择成为可能.如果您使用ID,请不要指定标记.所以$('#myId');比$('a#myId');使用原生javascript 快得多getElementById().如果指定标记,则它会采用更复杂的选择策略.此外,ID应该在DOM中是唯一的,因此不$("#content #second_nav ul.options_2 li a#photo") 使用$("#photo");.越短,越快越好.
如果您打算多次使用它们,请缓存所选的DOM元素:
var secondNav= $("#content #second_nav");
secondNav.toggle("fast");
Run Code Online (Sandbox Code Playgroud)为简洁起见,如果它们共享相同的操作,则可以在选择器中指定多个元素.例如:
var secondNav = $("#content #second_nav");
secondNav.toggle("fast");
$("ul.options_3, ul.options_2, ul.options_4",secondNav).hide();
$('.active_2').removeClass('active_2');
$('.active').removeClass('active');
$(this).toggleClass('selected');
Run Code Online (Sandbox Code Playgroud)希望这可以帮助...