0

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');
    }
}); 
4

2 回答 2

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
}); 
于 2017-06-29T03:06:07.147 回答
0

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

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

这将使函数全局可访问

于 2017-06-29T03:10:08.747 回答