为什么我的函数返回undefined,而我确实给它一个参数

时间:2018-06-05 11:31:58

标签: javascript jquery

这就是我的代码(完全)

的样子
function getPassword() {
    let pwd = ($('<input/>', {
   //unrelated code
    })).on('blur', function() {
        //more unrelated code
        } else {
            $(this).css({
                'color': 'gray',
                'border': '1px solid green'
            });
            let cValue = $(this).val();
            console.log(cValue);
            let x = getPasswordConfirm(cValue);
        }
    });
    return pwd;

}

function getPasswordConfirm(cValue) {
    let pwd = ($('<input/>', {
        //more unrelated code
    })).on('blur', function() {
        //unrelated code
        } else {
            if ($(this).val() !== cValue) {
                    console.log(cValue);
//this is where it goes wrong, cValue is undefined???
            } else {
                $(this).css({
                    'color': 'gray',
                    'border': '1px solid green'
                });
                console.log(cValue);
            }
        }
    });
    return pwd;
}

我遇到的问题是:我使用cValue作为参数,但它并没有传递给我的函数。当我在console.log cValue时,它在我的getPasswordConfirm()函数中返回undefined。要放大我调用函数的部分,并尝试将参数传递给参数:

else {
                $(this).css({
                    'color': 'gray',
                    'border': '1px solid green'
                });
                let cValue = $(this).val();
                console.log(cValue); //this works
                let x = getPasswordConfirm('haha');
            }
        });

这是我的函数中应该使用参数cValue:

评估当前值的部分
 else {
                if ($(this).val() !== cValue) {
                        console.log(cValue); //returns undefined
                } else {
                    $(this).css({
                        'color': 'gray',
                        'border': '1px solid green'
                    });
                    console.log(cValue);
                }

我如何追加/调用函数:

$(getEblock('col-md-6 col-md-offset-3').append(getLoginName(), getUsrName(), getPassword(), getPasswordConfirm()).appendTo('form'));

但无论我用作什么参数,它总是在我的getPasswordConfirm(cValue)函数中返回undefined。是的,我会调用这些函数(如你所见)。

3 个答案:

答案 0 :(得分:1)

请相信我,以前的答案是正确的方法,但是,如果您想尝试自己的流程,那么这里有一个解决方案,它会更慢,很多不需要的变量,那么多的编码等等,您可以玩来自jsbin

的代码
// declare global
// getting form by id (jquery), 
// it is always good practise to define your element in global scope
// we used $somename for jquery specific names
// remember $('somekelement') is a heavy function of jQuery 
// which did lots of calculation behind the scene
// this is why i am declaring it only once 
// it will help me to not used $('#myform') every time, need to access form 
var $myform = $('#myform');

// for your logic i wanted two extra boolean to check if my password and confirm_password i created or not.
var isPassword = false; // by default not created
var isConfirmPassword = false; // false means not created true means created.

// this is your function that create a input and some logic as per your requirements
function getPassword() {

  if(!isPassword) {
    let pwd = $('<input/>', {
          type:'text',
          name:'password',
         'placeholder':'Password'
       }).on('blur', function() {

          if(false) {
            //more unrelated code
          } else {
            $(this).css({
                'color': 'gray',
                'border': '1px solid green'
            });
            let cValue = $(this).val();

            console.log("Your cValue: "+ cValue); // here you are getting your values right.

            let x = getPasswordConfirm(cValue);   // here you are calling another function that generate another input
          }
        });
      return pwd;
      isPassword = true;
    }
};


// if this function is generating new input, then it must not be called inside of getPassword function, because blur event may occur multiple times and each blur will create new confirm_password fields
// here i think logically not possible, 
// only possible way here is to distribute your coding into two section
// 1st section will build all your dynamic input fields
// 2nd section will validate your inputs.
function getPasswordConfirm(cValue) {
  window.cValue = cValue; // i saved cValue here in global namespace so next time.
    console.log('argument cValue: '+cValue); // wola, you got the value here.

  // but sadly, you didn't have c_pwd yet, so you couldn't be able to fire blur event here.
  // Your blur event will be created but if will fire on out of focus, but next time cValue will not be passed
  // because it will happened only one time or you will have multiple inputs each trying to catch a event before born to the world
  if(!isConfirmPassword) {
    let c_pwd = ($('<input/>', {  // changed name to c_pwd
       type:'text',
       name:'confirm_password',
      'placeholder':'Confirm Password'
    })).on('blur', function() {
      console.log('What was cValue: '+ window.cValue);
        if(false) {
            //unrelated code
        } else {
            if ($(this).val() !== cValue) {
                    console.log('====rock you got cValue here : '+cValue); // getting this value here as well. but problem is that you are getting multiple inputs
                //this is where it goes wrong, cValue is undefined???
            } else {
                $(this).css({
                    'color': 'gray',
                    'border': '1px solid green'
                });
                console.log(cValue);
            }
        }
    }.bind(this)); // you can also bind your subscope to their parent scope by bind funciton, in new ES6 we create arrow function (arg1, arg2) => {console.log(arg1,arg2);}

    isConfirmPassword = true;

    //return c_pwd; // comment this line and uncomment next line see result by yourself. 
    $myform.append(c_pwd); // i am appending confirm_password input on blur on password result will create multiple confirm boxes   
  }
};


$myform.append(getPassword());

// suppose your two function build your form then code for appending will be like that
//$myform.append(getPassword()).append(getPasswordConfirm());

答案 1 :(得分:0)

问题是您在函数内部创建了一个事件处理程序(如果多次调用该函数,则不应该这样做,但这是另一回事了)。在创建处理程序时,已定义'cValue'。但是,在创建处理程序之后,该函数将退出(它已经完成了工作)。然后,当事件发生时,'cValue'不再被定义(因为外部函数早已完成并且cValue被垃圾回收了。

该问题的解决方案可能是外部函数将cValue的值存储在global variable中。然后,当事件发生时,请抓取此全局变量以指示事件处理程序并使用它。

答案 2 :(得分:0)

我建议您保持松散耦合的结构。因此,我建议将上下文传递给所有方法以进行跟踪和交互。如果需要,您也可以在以后使用此上下文来累积表单数据或其他目的。

let context = {}
$(getEblock('col-md-6 col-md-offset-3').append(
  getLoginName(context),
  getUsrName(context),
  getPassword(context),
  getPasswordConfirm(context)
).appendTo('form'));

function getPassword(context) {
  let pwd = ($('<input/>', {
    //unrelated code
  }))
  .on('blur', function() {
    //more unrelated code
    context.cValue = $(this).val();
  });
  return pwd;
}

function getPasswordConfirm(context) {
  let pwd = ($('<input/>', {
    //more unrelated code
  }))
  .on('blur', function() {
    if ($(this).val() !== context.cValue) {
      //password mismatch
    }
  });
  return pwd;
}