-3

所以我有一个运行良好的 jquery“复选框选中/未选中”功能。这是一个用于打开或关闭特定 URL 参数的复选框 - 但我相信这段代码可以写得更紧凑。有没有人有什么建议?

$('#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);
});
4

1 回答 1

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);
});
于 2013-08-28T18:28:40.593 回答