如何将此代码转换为jQuery的每个函数?

时间:2017-03-14 10:07:41

标签: jquery

如何将此代码转换为jQuery的每个函数?重复代码是不好的,我想添加更多输入字段,我看到我将创建更多变量,if和else语句,如果我将继续使用此代码。我认为jQuery的每个功能都将是解决这个问题的方法。对不起,我只是使用jQuery的新手。

    var username = $('input[name=username]');
    var firstname = $('input[name=firstname]');
    var lastname = $('input[name=lastname]');
    var result = '';
    if(username.val() == ''){
    	username.parent().addClass('has-error');
    }else{
    	username.parent().removeClass('has-error');
    	username.parent().addClass('has-success')
    	result +='1';
    }
    if(firstname.val() == ''){
    	firstname.parent().addClass('has-error');
    }else{
    	firstname.parent().removeClass('has-error');
    	firstname.parent().addClass('has-success')
    	result +='2';
    }
    if(lastname.val() == ''){
    	lastname.parent().addClass('has-error');
    }else{
    	lastname.parent().removeClass('has-error');
    	lastname.parent().addClass('has-success')
    	result +='3';
    }
    if(result == '123'){
    	$.ajax({
    		type: 'ajax',
    		method: 'POST',
    		url: url,
    		data: data,
    		async: false,
    		dataType: 'json',
    		success: function(response){
    			if(response.success){ 
    				$('#myModal').modal('hide');
    				$('#myForm')[0].reset();
    				if(response.type == "add"){
    					var type = 'added';
    				} else if(response.type == "edit"){
    					var type = 'updated';
    				}
    				$('.alert-success').html('User '+type+' succesfully').fadeIn().delay(4000).fadeOut('slow');
    				showAllUser();
    			} else{
    				alert('Error');
    			}
    		},
    		error: function(){
    			alert("Failed to add");
    		}
    	});
    }

3 个答案:

答案 0 :(得分:0)

你可以试试这个: -

var t = function {};
t.bar = function() { 
    console.log('bar'); 
};

t.bar();

答案 1 :(得分:0)

快速重构后......

var username = $('input[name=username]');
var firstname = $('input[name=firstname]');
var lastname = $('input[name=lastname]');

var valid = true;
var fields = [username, firstname, lastname];

$.each(fields, function(i, field) {
  if (field.val() == '') {
    field.parent().addClass('has-error');
    valid = false;
  } else {
    field.parent().removeClass('has-error');
    field.parent().addClass('has-success')
  }
});

if (valid) {
  $.ajax({
    type: 'ajax',
    method: 'POST',
    url: url,
    data: data,
    async: false,
    dataType: 'json',
    success: function(response) {
      if (response.success) {
        $('#myModal').modal('hide');
        $('#myForm')[0].reset();
        if (response.type == "add") {
          var type = 'added';
        } else if (response.type == "edit") {
          var type = 'updated';
        }
        $('.alert-success').html('User ' + type + ' succesfully').fadeIn().delay(4000).fadeOut('slow');
        showAllUser();
      } else {
        alert('Error');
      }
    },
    error: function() {
      alert("Failed to add");
    }
  });
}

答案 2 :(得分:0)

这个怎么样:

var hasErrors = false;
$('input[name=username], input[name=firstname], input[name=lastname]').each(function(index, elem) {

  var $elem = $(elem);

  if($elem.val() == ''){
      $elem.parent().addClass('has-error');
      hasErrors = true;
  }else{
      $elem.parent().removeClass('has-error');
      $elem.parent().addClass('has-success');
  }

});

if(!hasErrors){
    $.ajax({
        type: 'ajax',
        method: 'POST',
        url: url,
        data: data,
        async: false,
        dataType: 'json',
        success: function(response){
            if(response.success){ 
                $('#myModal').modal('hide');
                $('#myForm')[0].reset();
                if(response.type == "add"){
                    var type = 'added';
                } else if(response.type == "edit"){
                    var type = 'updated';
                }
                $('.alert-success').html('User '+type+' succesfully').fadeIn().delay(4000).fadeOut('slow');
                showAllUser();
            } else{
                alert('Error');
            }
        },
        error: function(){
            alert("Failed to add");
        }
    });
}