2013-08-28 41 views
-3

所以我有一個jquery「複選框選中/未選中」功能運行良好。這是一個打開或關閉特定URL參數的複選框 - 但我相信這些代碼可能會寫得更嚴格。有沒有人有什麼建議?如果複選框被選中或未選中 - 代碼優化 - jQuery的

$('#mapControl').live('click', function(){ 
    var thisUrl = $(location).attr('href'); 
    if($(this).is(':checked')) { 
     var lastFour = thisUrl.substr(thisUrl.length - 4); 
     var param; 
     if (lastFour == 'com/') {param='?mapControl=true'} else {param='&mapControl=true'} 
     thisUrl=thisUrl+param; 
    } else { 
     $('#urlParam').val(thisUrl); 
     if (thisUrl.indexOf('?mapControl=true') >= 0){ 
      thisUrl=thisUrl.replace('?mapControl=true',''); 
     } else if (thisUrl.indexOf('&mapControl=true') >= 0){ 
      thisUrl=thisUrl.replace('&mapControl=true',''); 
     } 
    } 
    $('#urlParam').val(thisUrl); 
}); 
+2

發表於http://codereview.stackexchange.com/ – Sergio

+4

這個問題屬於上http://codereview.stackexchange.com/ – Dom

+0

首先不使用live()方法(除非你使用的是jQuery的一個非常舊的版本)。 –

回答

0

儘量避免的jQuery儘可能比如,你可以

$('#mapControl').live('click', function(){ 
// you can directly read window location href attribute 
var thisUrl = window.location.href; 
var urlParamObj = $('#urlParam'); 
// instead of $(this).is(':checked') YOU can write *this.checked === true* 
if(this.checked === true) { 
    var lastFour = thisUrl.substr(thisUrl.length - 4); 
    var param; 
    if (lastFour == 'com/') {param='?mapControl=true'} else {param='&mapControl=true'} 
    thisUrl=thisUrl+param; 
} else { 
    urlParamObj.val(thisUrl); 
    /* if you are sure that your location may have "?mapControl=true" OR "&mapControl=true"you don't have to write code to check string directly replace 
    */ 
     thisUrl=thisUrl.replace('?mapControl=true',''); 
     thisUrl=thisUrl.replace('&mapControl=true',''); 
} 
// you don't have to write $('#urlParam') 2 times create a object and refer it again and again 
urlParamObj.val(thisUrl); 
}); 
相關問題