如何停止编写重复的代码

时间:2009-11-06 11:11:43

标签: jquery

您好,我只是想知道如何将下面的代码更改为更少的代码行,它包含很多重复的行,

它的基本操作是交换图像并让它们放大,

任何帮助将不胜感激,

 // JavaScript Document
$(function() {

    var fullWidth = 1500; // Width in pixels of full-sized image
    var fullHeight = 2000; // Height in pixels of full-sized image
    var thumbnailWidth = 327;  // Width in pixels of thumbnail image
    var thumbnailHeight = 480;  // Height in pixels of thumbnail image

    // Set size of div
    $('.big_product').css({
                    'width': thumbnailWidth+'px',
                    'height': thumbnailHeight+'px'
    }); 

  //on page load hide small product2 and small product3
  $('#small_product2,#small_product3').hide();

  var selected_color;
  //get the selected color
  $('#colors option').click(function() {
      selected_color = $('#colors option:selected').text().toLowerCase();

      //show the relevant product according to selected color
      if(selected_color == 'navy') {              
          $('#small_product2,#small_product3').hide();
          $('#small_product1').show();
      }

     else if(selected_color == 'grey') {
          $('#small_product1,#small_product3').hide();
          $('#small_product2').show();
      }

      else if(selected_color == 'black') {
          $('#small_product1,#small_product2').hide();
          $('#small_product3').show();
      }
 });

//hide the full-sized(the largest) pictures
$('#full1-1,#full1-2,#full1-3').hide();

//hide the thumbnails
$('#thumbnail1-1,#thumbnail1-2,#thumbnail1-3').hide();

//when the first small pic is clicked
$('#small_product1-1').click(function() {
    $('#main_product,#big_product1-2,#big_product1-3').hide();
    $('#big_product1-1,#thumbnail1-1').show();
});

// Toggle full and thumbnail pictures on click
$('#big_product1-1').click(function() {
    $('#thumbnail1-1').toggle();
    $('#full1-1').toggle();                 
});

// Do some calculations
    $('#big_product1-1').mousemove(function(e) {
        var mouseX = (e.pageX-400) - $(this).attr('offsetLeft'); 
        var mouseY = (e.pageY-400) - $(this).attr('offsetTop'); 

        var posX = (Math.round((mouseX/thumbnailWidth)*100)/100) * (fullWidth-thumbnailWidth);
        var posY = (Math.round((mouseY/thumbnailHeight)*100)/100) * (fullHeight-thumbnailHeight);

        $('#full1-1').css({
            'left': '-' + posX + 'px',
            'top': '-' + posY + 'px'
        });
  });

//when the second small pic is clicked
$('#small_product1-2').click(function() {
    $('#main_product,#big_product1-1,#big_product1-3').hide();
    $('#big_product1-2,#thumbnail1-2').show();
});

// Toggle full and thumbnail pictures on click
$('#big_product1-2').click(function() {
    $('#thumbnail1-2').toggle();
    $('#full1-2').toggle();                 
});

// Do some calculations
    $('#big_product1-2').mousemove(function(e) {
        var mouseX = (e.pageX-400) - $(this).attr('offsetLeft'); 
        var mouseY = (e.pageY-400) - $(this).attr('offsetTop'); 

        var posX = (Math.round((mouseX/thumbnailWidth)*100)/100) * (fullWidth-thumbnailWidth);
        var posY = (Math.round((mouseY/thumbnailHeight)*100)/100) * (fullHeight-thumbnailHeight);

        $('#full1-2').css({
                        'left': '-' + posX + 'px',
                        'top': '-' + posY + 'px'
        });
  });

//when the third small pic is clicked
$('#small_product1-3').click(function() {
    $('#main_product,#big_product1-1,#big_product1-2').hide();
    $('#big_product1-3,#thumbnail1-3').show();
});

// Toggle full and thumbnail pictures on click
$('#big_product1-3').click(function() {
    $('#thumbnail1-3').toggle();
    $('#full1-3').toggle();                 
});

// Do some calculations
    $('#big_product1-3').mousemove(function(e) {
        var mouseX = (e.pageX-400) - $(this).attr('offsetLeft'); 
        var mouseY = (e.pageY-400) - $(this).attr('offsetTop'); 

        var posX = (Math.round((mouseX/thumbnailWidth)*100)/100) * (fullWidth-thumbnailWidth);
        var posY = (Math.round((mouseY/thumbnailHeight)*100)/100) * (fullHeight-thumbnailHeight);

        $('#full1-3').css({
            'left': '-' + posX + 'px',
            'top': '-' + posY + 'px'
        });
  });
});

5 个答案:

答案 0 :(得分:2)

您已经看到,您的代码中有一些看起来非常相似的段落。试着找出一些差异,看看你是否可以进一步抽象。所以不要写3x

// Do some calculations
$('#big_product1-2').mousemove(function(e) {
  var mouseX = (e.pageX-400) - $(this).attr('offsetLeft'); 
  var mouseY = (e.pageY-400) - $(this).attr('offsetTop'); 

  var posX = (Math.round((mouseX/thumbnailWidth)*100)/100) * (fullWidth-thumbnailWidth);
  var posY = (Math.round((mouseY/thumbnailHeight)*100)/100) * (fullHeight-thumbnailHeight);

  $('#full1-2').css({
    'left': '-' + posX + 'px',
    'top': '-' + posY + 'px'
  });
});
$('#big_product1-2').click(function() {
$('#thumbnail1-2').toggle();
$('#full1-2').toggle(); 
你可以写

var doStuff = function(id) {
   $('#big_product'+id).mousemove(function(e) {
      var mouseX = (e.pageX-400) - $(this).attr('offsetLeft'); 
      var mouseY = (e.pageY-400) - $(this).attr('offsetTop'); 

      var posX = (Math.round((mouseX/thumbnailWidth)*100)/100) * (fullWidth-thumbnailWidth);
      var posY = (Math.round((mouseY/thumbnailHeight)*100)/100) * (fullHeight-thumbnailHeight);

      $('#full'+id).css({
        'left': '-' + posX + 'px',
        'top': '-' + posY + 'px'
      });
    });
$('#big_product'+id).click(function() {
$('#thumbnail'+id).toggle();
$('#full'+id).toggle(); 
}

并使用doStuff('1-2');调用它,依此类推......

答案 1 :(得分:1)

这部分:

//show the relevant product according to selected color
if(selected_color == 'navy') {                          
    $('#small_product2,#small_product3').hide();
    $('#small_product1').show();
}
else if(selected_color == 'grey') {
    $('#small_product1,#small_product3').hide();
    $('#small_product2').show();
}
else if(selected_color == 'black') {
    $('#small_product1,#small_product2').hide();
    $('#small_product3').show();
}

可以写成:

//show the relevant product according to selected color
$('#small_product1,#small_product2,#small_product3').hide();
if(selected_color == 'navy') {                          
    $('#small_product1').show();
}
else if(selected_color == 'grey') {
    $('#small_product2').show();
}
else if(selected_color == 'black') {
    $('#small_product3').show();
}

和重复的部分:

//when the third small pic is clicked
// Toggle full and thumbnail pictures on click
// Do some calculations

可以分解为函数。

答案 2 :(得分:1)

我喜欢表格驱动的代码。这意味着当您添加第四个或第五个控件时,答案会很好地扩展。它还很好地区分了数据与实现之间的关联。我没有运行下面的内容(我的PHP很弱)所以它是伪代码,但希望它会传递这个想法。

array control_colour_map = {
    { 'navy', 'small_product1',
    { 'grey', 'small_product2',
    { 'black', 'small_product3' }

for item in control_colour_map
{
    if( selected_colour = item.first )
        item.second.show()
    else
        item.second.hide()
}

如果有一个显示/隐藏函数采用布尔参数,它可能更短

for item in control_colour_map
    item.second.show( selected_colour = item.first )

答案 3 :(得分:0)

非常幸运的是,jQuery基于字符串(选择器)进行操作,所以你可以用它做很多技巧。

以下是我应用了我能想到的技巧的代码。由于我没有你的HTML代码,我也懒得创建一个,所以我无法测试这段代码。如果我在代码中出错了,请原谅我。 :-P

以下是代码:

// JavaScript Document

function swapSmallProduct(ShowID, MaxID) {
    var ToShow = "#small_product"+ShowID;
    $(ToShow).show();
    // Use loop or array to customize the id
    for(i = 1; i <= MaxID; i++) {
        var IDToHide = ((ShowID + i) % MaxID);
        var ToHide = "#small_product"+IDToHide;
        $(ToHide).hide();
    }
}

function hideAll_Full_and_Thumbnail(MaxID) {
    // Use loop or array to customize the id
    for(i = 1; i <= MaxID; i++) {
        $('#full1-'     +i).hide();
        $('#thumbnail1-'+i).hide();
    }
}

function toggle_BigProduct(ID, MaxID) {
    var ToShow = "#big_product1-"+ShowID+",#thumbnail1-"+ShowID;
    $(ToShow).show();

    $('#main_product').hide();
    for(i = 1; i <= MaxID; i++) {
        var IDToHide = ((ShowID + i) % MaxID);
        var ToHide = "#big_product"+IDToHide;
        $(ToHide).hide();
    }
}
function toggle_Full_and_Thumbnail(ID) {
    // Use function to generalize the id
    $('#thumbnail1-'+ID).toggle();
    $('#full1-'     +ID).toggle();
}

function getNumID(StrID) {
    var RegEx = /[0-9]+$/i;
    var Match = RegEx.exec(StrID);
    if (Match == null)
        return "";

    return 0+Match[0];
}


$(function() {

    var maxID = 3;
    var fullWidth = 1500; // Width in pixels of full-sized image
    var fullHeight = 2000; // Height in pixels of full-sized image
    var thumbnailWidth = 327;  // Width in pixels of thumbnail image
    var thumbnailHeight = 480;  // Height in pixels of thumbnail image

    // on page load hide small product2 and small product3
    $('#small_product2,#small_product3').hide();

    // Set size of div
    $('.big_product').css({
        'width':  thumbnailWidth +'px',
        'height': thumbnailHeight+'px'
    });

    var selected_color;
    //get the selected color
    $('#colors option').click(function() {
        selected_color = $('#colors option:selected').text().toLowerCase();
        // show the relevant product according to selected color
        // Use loop or array to customize the id
        if     (selected_color == 'navy')  swapSmallProduct(1, maxID);
        else if(selected_color == 'grey')  swapSmallProduct(2, maxID);
        else if(selected_color == 'black') swapSmallProduct(3, maxID);
    });

    // Use function to generalize the id
    hideAll_Full_and_Thumbnail(maxID);

    // Use prefix selector
    $(<i>"[id^='small_product1-']"</i>).click(function() {
        // and extract the ID to customize each click function
        var aNumID = getNumID($(this).attr("id"));
        // Use function to generalize the id
        toggle_BigProduct(aNumID, MaxID);
    }
    // Use prefix selector
    $(<i>"[id^='big_product1-']"</i>).click(function() {
        // and extract the ID to customize each click function
        var aNumID = getNumID($(this).attr("id"));
        // Use function to generalize the id
        toggle_Full_and_Thumbnail(aNumID);
    }

    // Use prefix selector
    $(<i>"[id^='big_product1-']"</i>).mousemove(function(e) {
        // and extract the ID to customize each click function
        var aNumID = getNumID($(this).attr("id"));

        var mouseX = (e.pageX-400) - $(this).attr('offsetLeft'); 
        var mouseY = (e.pageY-400) - $(this).attr('offsetTop'); 

        var posX = (Math.round((mouseX/thumbnailWidth )*100)/100) * (fullWidth  - thumbnailWidth);
        var posY = (Math.round((mouseY/thumbnailHeight)*100)/100) * (fullHeight - thumbnailHeight);

        $('#full1-'+aNumID).css({
            'left': '-' + posX + 'px',
            'top':  '-' + posY + 'px'
        });
    });
}

}

见粗体部分。

现在代码的大小可能不会那么小但现在可以更加可扩展(因为你可以拥有3个以上代码并且代码不会增长)而且它现在不太容易出错。

希望我能给你一些想法。

答案 4 :(得分:0)

我建议你阅读clean code。它允许开眼界