"函数"在Javascript中没有定义错误:调用我的函数的正确方法是什么?

Joe*_*oel 4 javascript jquery

我理解了一下因为这篇文章: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>
Run Code Online (Sandbox Code Playgroud)

tal*_*las 6

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>
Run Code Online (Sandbox Code Playgroud)

如果你真的想使用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>
Run Code Online (Sandbox Code Playgroud)

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