开发者

Help refactoring jquery snippet from ajax call

I'm trying to refactor this code. I have this jquery ajax call

    $.ajax({
       url: 'addMember',
       type: 'post',
       data: data,
       dataType: 'json',
       success: function(msg) {                                             
        if(msg.validate === false) {    // if there are validation errors...
                if(msg.firstName != '') {
                    $('input[name="firstName"]').parents('p').before(msg.firstName);
                    $('input[name="firstName"]').parents('p').prev('p').addClass('message error');
                    $('input[name="firstName"]').addClass('error');
                    $('input[name="firstName"]').after('<span class="check-error"></span>');
                }
                if(msg.lastName != '') {
                    $('input[name="lastName"]').parents('p').before(msg.lastName);
                    $('input[name="lastName"]').parents('p').prev('p').addClass('message error');
                    $('inp开发者_如何转开发ut[name="lastName"]').addClass('error');
                    $('input[name="lastName"]').after('<span class="check-error"></span>');
                }
                if(msg.email != '') {
                    $('input[name="email"]').parents('p').before(msg.email);
                    $('input[name="email"]').parents('p').prev('p').addClass('message error');
                    $('input[name="email"]').addClass('error');
                    $('input[name="email"]').after('<span class="check-error"></span>');
                }
         }
    .......etc

I tried doing this but that didn't work

$.each(msg, function(k, v)) {
    console.log('msg.k = '+msg.k);
});

Suggestions?


The jQuery way to do it is to chain your method calls, and avoid constantly reselecting the same element(s) from the DOM.

Change this:

$('input[name="firstName"]').parents('p').before(msg.firstName);
$('input[name="firstName"]').parents('p').prev('p').addClass('message error');
$('input[name="firstName"]').addClass('error');
$('input[name="firstName"]').after('<span class="check-error"></span>');

Into this:

$('input[name="firstName"]')
 .addClass('error')
 .after('<span class="check-error"></span>')
 .parents('p').before(msg.firstName)
   .prev('p').addClass('message error');

Secondly, it looks like you're simply performing the same action three times with three different values. This suggests a loop:

if(msg.validate === false) {    // if there are validation errors...
  $(['firstName', 'lastName', 'email']).each(function (i, e) {
    if (msg[e] != '') {
      $('input[name="' + e + '"]')
       .addClass('error')
       .after('<span class="check-error"></span>')
       .parents('p').before(msg[e])
         .prev('p').addClass('message error');
    }
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜