简体   繁体   English

在另一个函数中调用JS函数

[英]Calling JS function in another function

I am trying to call a function inside another function but its not working. 我正在尝试在另一个函数中调用一个函数,但是它不起作用。

PS i am a beginnner in JS PS我是JS的初学者

<script type="text/javascript">
    <!--
    // Form validation code will come here.
    function validate() {
        madatorychk(name);
        //This functions makes sure that madatory fields are filled
        function madatorychk(fieldid) {
            var node = document.myForm.fieldid;
            if (node.value == "") {
                alert("This field cannot be left empty");
                document.myForm.fieldid.focus();
                return false;
            }

        }
    }
    //-->
</script> 

<form method="get" onsubmit="return(validate());"  name="myForm">
    <label>Name: <input type="text" id="name"></label> </form>
</form>

You need to use bracket notation to access object properties with variable name. 您需要使用括号符号来访问具有变量名称的对象属性。

So document.myForm.fieldid (it tries to take a form element with the name literally fieldid ) is not correct and should be document.myForm[fieldid] : 因此, document.myForm.fieldid (它试图采用名称实际上为fieldid的表单元素)是不正确的,应该为document.myForm[fieldid]

function validate() {

    return madatorychk('name');

    //This functions makes sure that madatory fields are filled
    function madatorychk(fieldid) {
        var node = document.myForm[fieldid];
        if (node.value == "") {
            alert("This field cannot be left empty");
            document.myForm[fieldid].focus();
            return false;
        }
    }
}

For this also make sure you have named form element: 为此,还要确保已命名表单元素:

Name: <input type="text" name="name" />

And finally, very important is that you need to return result of madatorychk : 最后,非常重要的一点是您需要返回madatorychk结果:

return madatorychk('name');

One more thing. 还有一件事。 You probably don't want to allow not only empty but also usernames with just spaces, so trim input before validation: 您可能不希望不仅允许空白,而且不允许只包含空格的用户名,所以在验证之前修剪输入:

if (node.value.trim() == "") {
    alert("This field cannot be left empty");
    document.myForm[fieldid].focus();
    return false;
}

Demo: http://jsfiddle.net/747twprf/ 演示: http //jsfiddle.net/747twprf/

You have a few errors: 您有一些错误:

  • you pass name (nothing) instead of "name" 您传递name (什么都没有)而不是"name"
  • you don't return from the internal function 您不会从内部函数返回
  • you get the property called "fieldid" instead of the one whose name is in fieldid 您将获得名为"fieldid"的属性,而不是名称为fieldid

Here's a fixed code: 这是一个固定的代码:

function validate() {
     return madatorychk("name"); // note the return and the "name"
     function madatorychk (fieldid) {
        var node = document.myForm[fieldid]; // note the [fieldid]
        if (node.value == "" ) {
            alert("This field cannot be left empty");
            document.myForm[fieldid].focus() ;
            return false;
        }
     }
}

put function declaration outside of validate function. 将函数声明置于validate函数之外。

 //This functions makes sure that madatory fields are filled
             function madatorychk (fieldid) {
               var node = document.myForm.fieldid;
               if (node.value == "" ) {
               alert("This field cannot be left empty");
               document.myForm.fieldid.focus() ;
               return false;
             }  


        function validate(){
          madatorychk(name);


        }

Well, the following works for me: 好吧,以下对我有用:

<script>
    // Form validation code will come here.
    function validate()
    {
        madatorychk(name);
        //This functions makes sure that madatory fields are filled
        function madatorychk (fieldid) {
            var node = document.querySelector('#name');
            if (node.value == "" ) {
                alert("This field cannot be left empty");
                node.focus();
                return false;
            }

        }
    }
</script>
<form method="get" name="myForm" onsubmit="return validate();">
    <label>Name: <input type="text" id="name"></label> </form>
</form>

I changed the value of the onsubmit attribute and document.myForm.fieldid was not a valid element path. 我更改了onsubmit属性的值, document.myForm.fieldid不是有效的元素路径。

Example here . 这里的例子。

Prior to JavaScript 1.2, function definition was allowed only in toplevel global code but JavaScript 1.2 allows function definitions to be nested within other functions as well. 在JavaScript 1.2之前,仅在顶级全局代码中允许使用函数定义,但是JavaScript 1.2允许将函数定义也嵌套在其他函数中。

Still there is a restriction that function definitions may not appear within loops or conditionals. 仍然有一个限制,即函数定义不能出现在循环或条件中。 These restrictions on function definitions apply only to function declarations with the function statement. 这些对函数定义的限制仅适用于带有函数语句的函数声明。

But still the best way to do this would be to define the functions separately and just call it inside the first function , since the second function is a pretty handy function and could be used elsewhere. 但是,执行此操作的最佳方法仍然是分别定义函数,然后在第一个函数内部调用它 ,因为第二个函数非常方便,可以在其他地方使用。 Also use 'id' to recognize a form rather than using a name to do so. 也可以使用“ id”来识别形式,而不要使用名称来识别形式 And passing the node itself as argument would help you use the same function for any node of any form : 并且将节点本身作为参数传递将帮助您对任何形式的任何节点使用相同的函数

//This functions makes sure that mandatory fields are filled
 function mandatoryChk(node) {
    if (node.value == "" ) {
      alert("This field cannot be left empty");
      node.focus();
      return false;
    }
    else
      return true;
 }
 function validate() {
    var Name =  document.getElementById("myForm").elements['name'];
    return mandatoryChk(Name);
 }

And use the following HTML: 并使用以下HTML:

<form method="get" onsubmit="validate();"  id="myForm">
    <label>Name: <input type="text" id="name" name="name"></label>
    <input type='submit' value='Submit'/>
</form>

List of changes done: 所做更改的列表:

  • Changed the 'name' property of the form to 'id' property and added 'name' property to the text input. 将表单的“名称”属性更改为“ id”属性,并将“名称”属性添加到文本输入中。 Use id to recognize forms and names to recognize inputs. 使用id识别表单,使用名称识别输入。
  • Included a submit button, without which most browsers do not submit forms. 包括一个提交按钮,大多数浏览器不提交按钮不提交表单。
  • Changed the function call in the 'onsubmit' event in the form. 在窗体的“ onsubmit”事件中更改了函数调用。 The 'onsubmit' event from an HTML form is not recommended though. 但是不建议使用HTML表单中的“ onsubmit”事件。
  • Separated mandatoryChk() and validate() functions for the sake of 'code-reuse'. 为了“代码重用”,将强制Chk()和validate()函数分开。
  • Renamed mandatorychk() to mandatoryChk() to suit the Coding Conventions (see: Coding Conventions ) 为了符合编码约定,将更正的chk()重命名为constantChk()(请参阅: 编码约定
  • The input node has been defined already in the validate function and this node is then passed to the mandatoryChk() function. 已经在validate函数中定义了输入节点,然后将该节点传递给strictChk()函数。 This makes mandatoryChk() able to perform the checking on any text input of any form. 这使强制性Chk()能够对任何形式的任何文本输入执行检查。
  • Added alternative return value for True cases, mandatoryChk(). 为True案例添加了替代返回值,强制Chk()。

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

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