Javascript 中未定义“函数”错误:调用我的函数的正确方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8334442/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 03:05:18  来源:igfitidea点击:

"function" is not defined error in Javascript: what is the right way to call my function?

javascriptjquery

提问by Joel

I understand a bit because of this post: JQuery, setTimeout not workingwhy it's not working, but keeping everything this way, what is the right way to call _finalvalidate()inside my div?

由于这篇文章我有点理解:JQuery,setTimeout 不起作用,为什么它不起作用,但保持一切正常,_finalvalidate()在我的 div 中调用的正确方法是什么?

 <script type="text/javascript">

$(document).ready(function(){

//On Submitting
function _finalvalidate(){
    alert('ppp');
    if(validateName() & validateEmail() & validatePhone()){
        alert('OK');
        return true
    }
    else{
        alert('false');
        return false;
    }
}
});

</script>


<div onclick="_finalvalidate();"> Take action </div>

回答by talnicolas

The jQuery way of doing it would be something like:

jQuery 的做法是这样的:

<script type="text/javascript">

    $(document).ready(function(){

        //When clicking on the div, execute this 
        $("#validation").click(function() {
            alert('ppp');
            if(validateName() & validateEmail() & validatePhone()){
                alert('OK');
                return true
            }
            else{
                alert('false');
                return false;
            }
        });
    });

</script>
....
<div id="validate"> Take action </div>

If you really want to use the javascript function style, you gonna have to put the function outside the document.ready()function and then you'll be able to call it with the onclickattribute:

如果你真的想使用 javascript 函数风格,你必须把函数放在函数之外document.ready(),然后你就可以用onclick属性调用它:

<script type="text/javascript">

    function _finalvalidate(){
        alert('ppp');
        if(validateName() & validateEmail() & validatePhone()){
            alert('OK');
            return true;
        }
        else{
            alert('false');
            return false;
        }
    }   


</script>
....
<div onclick="_finalvalidate();"> Take action </div>

In this case you don't have anymore jQuery involved.

在这种情况下,您不再涉及 jQuery。

回答by Alex Wayne

You should bind your events with jQuery's events, if you are using jQuery. But as far as why it doesn't work, here is some info about JS scoping rules.

如果您使用 jQuery,您应该将您的事件与 jQuery 的事件绑定。但至于为什么它不起作用,这里有一些关于 JS 范围规则的信息。



Any function that you declare to be used later on should NOT be in the jquery document ready callback. You can't get it because it's hidden inside a function, which provides it's own private scope that you cannot get to from outside.

您声明以后要使用的任何函数都不应该出现在 jquery 文档就绪回调中。您无法获取它,因为它隐藏在一个函数中,该函数提供了您无法从外部访问的私有范围。

var f = function() {
  var inner = function() {};
};
inner(); // out of scope

You could export it to the global object, making it available everywhere.

您可以将其导出到全局对象,使其随处可用。

var f = function() {
  window.inner = function() {};
};
inner(); // works!

but the best way is to simply declare it in the global scope in the first place.

但最好的方法是首先在全局范围内简单地声明它。

var f = function() {}; // Now this function has no purpose anymore at all!
var inner = function() {};
inner(); // works

回答by C???

Your function doesn't exist in the scope of the window where you're trying to call it. I would change your code to:

您的函数不存在于您尝试调用它的窗口范围内。我会将您的代码更改为:

<div id="action">Take Action</div>

And then your JavaScript becomes:

然后你的 JavaScript 变成:

<script type="text/javascript">

$(document).ready(function(){

    //On Submitting
    $('#action').click(function() {
        alert('ppp');
        if(validateName() & validateEmail() & validatePhone()){
            alert('OK');
            return true
        } else {
            alert('false');
            return false;
        }
    });

</script>

回答by jfriend00

The issue with your code is that your function is not defined in the global context, but rather it's defined inside the document.ready callback function. So, when the browser gets the onclick and does an eval of your string, it doesn't find that function name in the global context. You can fix it a number of different ways:

您的代码的问题在于您的函数不是在全局上下文中定义的,而是在 document.ready 回调函数中定义的。因此,当浏览器获取 onclick 并对字符串执行 eval 时,它不会在全局上下文中找到该函数名称。您可以通过多种不同的方式修复它:

1) Change your function to be defined in the global scope like this:

1)将您的函数更改为在全局范围内定义,如下所示:

//On Submitting
window._finalvalidate = function(){

2) Move your _finalvalidate()function outside of the document.ready()so it's in the global scope. There is no reason for it to be in document.ready()because it is not executing right away.

2) 将您的_finalvalidate()函数移出 the 之外,document.ready()使其在全局范围内。没有理由让它进入,document.ready()因为它没有立即执行。

3) Change to the "jQuery" way of specifying event handlers rather than putting onclick=xxx in your HTML as Cory has illustrated in his answer.

3)更改为指定事件处理程序的“jQuery”方式,而不是像 Cory 在他的回答中说明的那样将 onclick=xxx 放在 HTML 中。

回答by Peter

If you want your method to be called from the div's onclick attribute, you'll need to make it available in the global scope. Below are some options. However, I should point out that Option 1 is generally frowned upon these days and Option 2 is just silly. The recommended approach for this kind of thing is to wire up your event handlers unobtrusively, as in Cory's answer.

如果您希望从 div 的 onclick 属性调用您的方法,则需要使其在全局范围内可用。下面是一些选项。然而,我应该指出,选项 1 现在普遍不受欢迎,而选项 2 只是愚蠢的。此类事情的推荐方法是不显眼地连接您的事件处理程序,如 Cory 的回答。

Option 1

选项1

<script type="text/javascript">

function _finalvalidate(){
    alert('ppp');
    if(validateName() & validateEmail() & validatePhone()){
        alert('OK');
        return true
    }
    else{
        alert('false');
        return false;
    }
}

</script>


<div onclick="_finalvalidate();"> Take action </div>

Option 2

选项 2

<script type="text/javascript">

var _finalvalidate;

$(document).ready(function() {
    _finalvalidate = function(){
        alert('ppp');
        if(validateName() & validateEmail() & validatePhone()){
            alert('OK');
            return true
        }
        else{
            alert('false');
            return false;
        }
    };
});

</script>


<div onclick="_finalvalidate();"> Take action </div>

回答by JesseBuesking

To keep it in jQuery, I'd give your div an id tag and call it using a jQuery onclick event. Also are you sure you want to be doing bitwise &operations in your if, or logical ands &&?

为了将它保留在 jQuery 中,我会给你的 div 一个 id 标签并使用 jQuery onclick 事件调用它。此外,您确定要&在 if 或逻辑 ands 中进行按位运算&&吗?

<script type="text/javascript">

$(document).ready(function() {
    $('#callme').click(function() {
        alert('ppp');
        if(validateName() && validateEmail() && validatePhone()){
            alert('OK');
            return true;
        } else {
            alert('false');
            return false;
        }
    }
});

</script>

<div id="callme"></div>