简体   繁体   English

我如何优化此JavaScript

[英]How can i optimize this JavaScript

I'm using the following JavaScript to toogle some information in my menu. 我正在使用以下JavaScript在菜单中添加一些信息。

Is it possible to optimize it so I only have one function instead of n? 有可能优化它,以便我只有一个函数而不是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 . 您可以使用for循环并创建IIFE来保留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. 首先,您只需要一个$(document).ready调用,这样就可以对其进行一些优化。 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: 理想情况下,您不会在元素上使用ID,只需按它们之间的关系引用它们即可,例如:

$(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: 如果可能,请将一个类添加到所有“可点击的” div中,然后尝试执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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