简体   繁体   English

函数的返回值返回未定义

[英]Return value from a function returns undefined

I have an html which has a form that a user could enter url if the value of the input text has www. 我有一个html格式,如果输入文本的值具有www,则用户可以输入url。 in it i will create a variable and return it to the function then pass it to the ajax but it seems that when I check it(ajaxData var) in the console it says undefined. 在其中,我将创建一个变量并将其返回给函数,然后将其传递给ajax,但是当我在控制台中检查它(ajaxData var)时,它似乎未定义。

<form action="" id="defaultForm">
  <input type="text" id="url">
  <button id="submit">Submit</button>
</form>

JS: JS:

$(function () {
   function myreturnValue() {
      $('#defaultForm').submit(function () {

         var w = 'www.';
         var current = $('#url').val();
         var appendW = w + current;

         if (current.match('www.')) {
            console.log('it already consists of www');
            var returnValue = 'site_url:' + current; //site_url:www.domain.com or http://
            console.log(typeof returnValue);
            return returnValue;
         } else {
            var returnValue = 'site_url:' + appendW; //www+url
            console.log(current);
            console.log(appendW);
            console.log(returnValue);
            return returnValue;
         }
      }); //end submit
   }
   var ajaxData = myreturnValue();
   console.log(typeof ajaxData);
   var data = 'data:{' + ajaxData + '}';
});

then in the ajax I will pass the data variable. 然后在ajax中,我将传递数据变量。 I hope my explanation is kinda clear. 我希望我的解释很清楚。

A few problems here. 这里有几个问题。

Calling $('#defaultForm').submit(function () { binds a submit handler to the form. It does not submit the form nor execute the function. Please familiarize yourself with the documentation . 调用$('#defaultForm').submit(function () {将提交处理程序绑定到表单。它不会提交表单也不执行函数。请熟悉文档

Your myreturnValue() doesn't return anything. 您的myreturnValue()不返回任何内容。 You only have one top level line which is the above submit binding. 您只有一个顶层行,即上面的提交绑定。 Not only is it not executed, but return inside that function does not propagate up like you're expecting it to. 它不仅不会执行,而且在该函数内部的return不会像您期望的那样向上传播。 Returning inside an event handler won't do anything in any context. 返回事件处理程序内部在任何情况下都不会执行任何操作。

Don't declare vars inside if branches in general. 通常不要在if分支内声明vars

Here's a quick attempt to reorganize this code, but with this many problems the corrected code may depend on your specific needs. 这是重新组织此代码的快速尝试,但是由于存在许多问题,更正后的代码可能取决于您的特定需求。

(function () {
    $('#defaultForm').submit(function (event) {

        // prevent default form submit
        event.preventDefault();

        var w = 'www.';
        var current = $('#url').val();
        var appendW = w + current;
        var value;

        if (current.match('www.')) {
            console.log('it already consists of www');
            value = 'site_url:' + current; //site_url:www.domain.com or http://
            console.log(typeof returnValue);
        } else {
            value = 'site_url:' + appendW; //www+url
            console.log(current);
            console.log(appendW);
            console.log(returnValue);
        }

        var data = 'data:{' + ajaxData + '}';

        // Do whatever you want with data here

    });

    // If you want to now submit the form by hand...
    $('#defaultForm').submit();

});

Currently in your code, myreturnValue function only execute a code to register an event listener to your form, without return value (your return statement will only be triggered on submit event), so that's why it will return undefined at the first time. 目前在你的代码, myreturnValue函数只执行代码以注册事件侦听器的形式,没有返回值(您return语句只会在触发submit事件),所以这就是为什么它会在第一时间返回undefined。

Try this: 尝试这个:

  • Put your url detect logic in myreturnValue function 将网址检测逻辑放入myreturnValue函数中
  • Then put a code to prevent default submit event to be fired 然后放入代码以防止触发默认的提交事件
  • Finally register a event listener for submit button. 最后注册一个事件监听器以提交按钮。

And your original regex www. 和您原始的正则表达式www. means match www with one other character, like wwww. 表示将www与其他字符匹配,例如wwww。 and www0. 和www0。 will be valid. 将有效。 You may consider changing it to other regex like this one 您可以考虑将其更改为其他正则表达式像这样一个

 $(function() { function myreturnValue() { var w = 'www.'; var current = $('#url').val(); var appendW = w + current; if (current.match(w)) { console.log('it already consists of www'); var returnValue = 'site_url:' + current; //site_url:www.domain.com or http:// console.log(typeof returnValue); return returnValue; } else { var returnValue = 'site_url:' + appendW; //www+url console.log(current); console.log(appendW); console.log(returnValue); return returnValue; } } $('#defaultForm').submit(function(e) { e.preventDefault(); }); $('#submit').on('click', function() { var data = 'data:{' + myreturnValue() + '}'; console.log(data); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form action="" id="defaultForm"> <input type="text" id="url"> <button id="submit">Submit</button> </form> 

In your code, the myreturnValue() is only return the returnValue of the function in Submit. 在您的代码中,myreturnValue()仅返回Submit中函数的returnValue。 'myreturnValue' function return anything because it doesn't any return value. 'myreturnValue'函数返回任何内容,因为它没有任何返回值。

You executed unnecessary function to get the ajaxData. 您执行了不必要的功能来获取ajaxData。 To get the ajaxData, You only need to 要获取ajaxData,您只需要

$('#defaultForm').submit(function () {
    contents
}

If fix the code simple... 如果简单地修复代码...

$('#defaultForm').submit(function () {
  var returnValue;
  var w = 'www.';
  var current = $('#url').val();
  var appendW = w + current;

  if (current.match('www.')) {
    console.log('it already consists of www');
    returnValue = 'site_url:' + current;   //site_url:www.domain.com or http://
    console.log(typeof returnValue);
  } else {
    returnValue = 'site_url:' + appendW; //www+url
    console.log(current);
    console.log(appendW);
    console.log(returnValue);
  }
  console.log(typeof returnValue);
  var data = 'data:{' + ajaxData + '}';
  console.log('data : ', data)
});

Please, Note : http://codepen.io/onyoon7/pen/mRdJJV 请注意: http : //codepen.io/onyoon7/pen/mRdJJV

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM