简体   繁体   中英

How I prevent code duplication in jquery?

I have to use same block of jQuery code several time in my page. Only changing selector names and url parameters.

My code look something like this:

$(document).ready(function () {  
  $("#year").change(function() {
    var url = ''; 
    var c = $("#category").val(); 
    var d = $(this).val(); 
    if(c.trim().length) { url+='&cat='+c } 
    if(d.trim().length) { url+='&mth='+d } 
    location.href="?p=summery"+url;  
  })

  $("#category").change(function() {
    var url = ''; 
    var c = $(this).val();
    var d = $("#year").val();
    if(d.trim().length) { url+='&mth='+d } 
    if(c.trim().length) { url+='&cat='+c } 
    location.href="?p=summery"+url;  
  })
});


$(document).ready(function () {  
  $("#year2").change(function() {
    var url = ''; 
    var c = $("#category2").val(); 
    var d = $(this).val(); 
    if(c.trim().length) { url+='&cat='+c } 
    if(d.trim().length) { url+='&mth='+d } 
    location.href="?p=card"+url;  
  })

  $("#category2").change(function() {
    var url = ''; 
    var c = $(this).val();
    var d = $("#year2").val();
    if(d.trim().length) { url+='&mth='+d } 
    if(c.trim().length) { url+='&cat='+c } 
    location.href="?p=card"+url;  
  })
});

$(document).ready(function () {  
  $("#year3").change(function() {
    var url = ''; 
    var c = $("#category3").val(); 
    var d = $(this).val(); 
    if(c.trim().length) { url+='&cat='+c } 
    if(d.trim().length) { url+='&mth='+d } 
    location.href="?p=chart"+url;  
  })

  $("#category3").change(function() {
    var url = ''; 
    var c = $(this).val();
    var d = $("#year3").val();
    if(d.trim().length) { url+='&mth='+d } 
    if(c.trim().length) { url+='&cat='+c } 
    location.href="?p=chart"+url;  
  })
});

There are lot of code duplication. My question is, can any body help me to prevent this code duplication. Reason is, I have to this code block for lot of selectors and urls .

Hope somebody may help me out. Thank you.

Extract the common code into a function:

function navigateBasedOnInput(monthInput, categoryInput, urlFragment) {
    var url = '',
          category = $(categoryInput).val(),
          month = $(monthInput).val();

    if (category.trim().length) {
        url += '&cat=' + encodeURIComponent(category);
    }
    if (month.trim().length) {
        url += '&mth=' + encodeURIComponent(month);
    }

    location.href = "?p=" + encodeURIComponent(urlFragment) + url;
}

$(document).ready(function () {
    $("#year, #category").change(function() {
        navigateBasedOnInput('#year', '#category', 'summery');
    });

    $("#year2, #category2").change(function() {
        navigateBasedOnInput('#year2', '#category2', 'card');
    });

    $("#year3, #category3").change(function() {
        navigateBasedOnInput('#year3', '#category3', 'chart');
    });
});

Try moving the common stuff out into a function.

function commonFunc(c, d, pStr) {
    var url = '';
    if (d.trim().length) {
        url+='&mth='+d;
    } 
    if (c.trim().length) { 
        url+='&cat='+c;
    } 
    return pStr+url;
}

Then in the change function it will be:

$("#year").change(function() {
    var c = $("#category").val(); 
    var d = $(this).val(); 
    location.href = commonFunc(c, d, '?p=chart');  
  });

Plus you can also put all the listeners in one ready function

[EDIT] It's a good habbit to add ; to the end of your statements

maybe you can do it like this:

var urls={
  year1:"",
  year2:"",
  year3:""
};
["year1","year2","year3"].forEach(function(e){
    var self = $("#"+e);
    self.change(function(){
        var url = urls[e], 
        c = self.val(),
        d = $(this).val(); 
        if(c.trim().length) { url+='&cat='+c } 
        if(d.trim().length) { url+='&mth='+d } 
        location.href="?p=card"+url;  
    });
});

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