2016-08-03 134 views
0

嗨有其他方法可以缩短此代码吗?我在一个页面中有多个表单,所以我需要通过ID来定位它。缩短代码

$('#documents_valid_id .dz-remove').click(function(){ 
    $('#documents_valid_id').removeClass('doc-upload-error'); 
}); 

$('#documents_proof_billing .dz-remove').click(function(){ 
    $('#documents_proof_billing').removeClass('doc-upload-error'); 
}); 

$('#documents_proof_income .dz-remove').click(function(){ 
    $('#documents_proof_income').removeClass('doc-upload-error'); 
}); 

回答

1

是的。您可以使用常用类.dz-remove选择该元素,因为该类仅适用于要从中删除doc-upload-error类的元素。

你只需要做一次。像这样:

$('.dz-remove').click(function(){ 
    $(this).parent().removeClass('doc-upload-error'); 
}); 

或者您也可以添加自定义类,你想从你自己删除类以及$('.class-name')发现它在jQuery的任何元素,那么你现在正在做同样的事情。

如果您想选择.dz-remove只有那些ID内,你仍然可以使它像这样的工作:

$('#documents_valid_id .dz-remove, 
    #documents_proof_billing .dz-remove, 
    #documents_proof_income .dz-remove' 
).click(function(){ 
    $(this).parent().removeClass('doc-upload-error'); 
}); 

注:这种方法将如果您包含.dz-remove类元素不是第1级的孩子失败你的表格。这意味着它会失败,如果你的html看起来像这样:

<form id="document_valid_id"> 
    <ul> 
     <li class="dz-remove"> 
..... 
</form> 

如果你能显示你的html也会有帮助。

0

考虑重构,让您的代码DRY

function bindUploadErrorRemovalClickEvent(id) { 
    var elementWithId = $('#' + id); 
    elementWithId.find('.dz-remove').on('click', function() { 
     elementWithId.removeClass('doc-upload-error'); 
    }); 
} 

bindUploadErrorRemovalClickEvent('documents_valid_id'); 
// ... and so on 
0

检查:

   $('.dz-remove').click(function(){ 
        var id = $(this).attr("id"); 
        $('#'+id).removeClass('doc-upload-error'); 
       });