开发者

I have 3 functions I am trying to put into a Switch Case

开发者 https://www.devze.com 2023-03-23 09:43 出处:网络
Here are the functions: function blockLayer1(){ $(\'#block1\').click(function() { $(\"#layer1\").toggle();

Here are the functions:

function blockLayer1(){
    $('#block1').click(function() {
        $("#layer1").toggle();
    });
        }

function blockLay开发者_JS百科er2(){
$('#block2').click(function() {
    $("#layer2").toggle();
});
    }

function blockLayer3(){
$('#block3').click(function() {
    $("#layer3").toggle();
});
  }

Here is the case that is not working:

$("#block").click(function(evt) {

 switch ($("#layer_container").index(this)) {
    case 0 :
    $("#layer1").toggle();
    break;
    case 1 :
    $("#layer2").toggle();
    break;
    case 2 :
    $("#layer3").toggle();
    break;

   }
 });
}


I would try abstracting this a bit further and just create one function:

function blockLayer(layerNum) {
    $('#block' + layerNum).click(function() {
        $("#layer" + layerNum).toggle();
    });
}

You have the same elements of code repeating except 1 part (the number), so it makes for a good case to abstract & simplify.

0

精彩评论

暂无评论...
验证码 换一张
取 消