导入的js函数抛出未定义的错误

时间:2017-06-29 02:58:57

标签: javascript jquery undefined-function

尝试从静态文件执行函数时,我收到此错误validate_allocation is not defined。知道为什么吗?

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="static/main.js"></script>
<script>
validate_allocation();
</script>

main.js

$(function() {
    alert('test'); // I can see this, so the file is imported for sure
    function validate_allocation(){
        alert('test');
    }
}); 

2 个答案:

答案 0 :(得分:0)

$(function() { ... });的目的是在页面加载后在中运行代码。正如其他人所说,你不仅在页面加载完成后(因此在HTML文件中调用之后)定义了一个函数,但它也仅限于该块的范围。它可以安全地移出块:

// Declare function at the root of the document and make it accessible to the HTML page
function validate_allocation(){
    alert('test');
}

// Actions to perform when the page has completed loading
$(function() {
    alert('test'); // I can see this, so the file is imported for sure
}); 

答案 1 :(得分:0)

从jquery onload函数中删除Validate_allocation函数。由于您正在编写该函数,因此它将仅限于该函数。

function validate_allocation(){
        alert('test');
    }
$(function() {
    alert('test'); // I can see this, so the file is imported for sure    
}); 

这将使该功能可全局访问