简体   繁体   中英

How can i optimize this JavaScript

I'm using the following JavaScript to toogle some information in my menu.

Is it possible to optimize it so I only have one function instead of n?

$(document).ready(function(){
 $("#km1").click(function(){
   $("#km1tog").slideToggle("slow");
 });
}); 

$(document).ready(function(){
 $("#km2").click(function(){
   $("#km2tog").slideToggle("slow");
 });
}); 

$(document).ready(function(){
 $("#km3").click(function(){
   $("#km3tog").slideToggle("slow");
 });
}); 

try:

$(document).ready(function(){
  $("#km1,#km2,#km3").click(function(){
    $("#"+this.id+"tog").slideToggle("slow");
  });
});

You can use for loop and create an IIFE, to retain the value of i .

$(document).ready(function() {
    for (var i = 1; i <= 3; i += 1) {
        (function(i) {
            $("#km" + i).click(function() {
                $("#km" + i + "tog").slideToggle("slow");
            });
        }(i));
    }
});

For a start you only need one $(document).ready call, so that will optimise it slightly. As for the rest, it depends greatly on the structure of the markup.

Ideally you wouldn't use ID's on the elements, you would simply reference them by their relationship, for example:

$(document).ready(function(){
    $(".top-menu").click(function(){
        $(this).find(".sub-menu").slideToggle("slow");
    });
}); 

Have you tried this?

$(document).ready(function() {
    $.each([1,2,3,4,5,6,7,8,9,10], function(i) {
        $("#km" + i).click(function(){
            $("#km" + i + "tog").slideToggle("slow");
        });
    });
});

If possible add a class to all of your "clickable" divs and try something like this:

$(document).ready(function(){
    $(".km").click(function(){
        id = $(this).attr('id');
        $("#"+id+"tog").slideToggle("slow");
    });
}); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM