使用带有文档对象的回调函数

时间:2013-08-12 05:01:57

标签: javascript

回拨功能适用于:

function mySandwich(param1, param2, callback) {  
    alert('Started eating my sandwich.\n\nIt has: ' + param1 + ', ' + param2);  
    callback();  
}  

mySandwich('ham', 'cheese', function() {  
    alert('Finished eating my sandwich.');  
}); 

在body body标签中。

当我尝试时:

<html>
<head>
<script>
    function CallAfterLogin()
    {
        document.mySandwich('hi',function(send){ 
        alert("finished");
        });
    }
</script>
</head>
<body>
<button type="button" onclick="CallAfterLogin()">Click Me!</button> 
<script>
    function mySandwich(param1, callback) {  
        alert('Started eating my sandwich.\n\nIt has: ' + param1 );  
        callback();  
    }  
</script>
</body>
</html>

它给出了错误:未定义document.mySandwich。 有人能告诉我问题在哪里吗?

1 个答案:

答案 0 :(得分:2)

mySandwich不是附加到文档对象的函数,它是全局范围内的函数,因此只需使用document.mySandwich(...)而不是mySandwich(...)

function CallAfterLogin() {
    mySandwich('param1', 'param2', function(send){ 
        alert("finished");
    });
}