且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

javascript通过脚本标签定义范围?

更新时间:2023-12-04 23:51:40

这不是范围问题。如果在一个脚本元素中定义一个函数(在全局范围内),则可以在另一个脚本元素中使用它。

This isn't a scope issue. If you define a function (in the global scope) in one script element, then you can use it in another.

但是,脚本元素将按原样进行解析和执行遇到。

However, script elements are parsed and executed as they are encountered.

提升不适用于脚本元素。在较早的脚本元素的初始运行期间,在稍后的脚本元素中定义的函数将不可用。

Hoisting won't work across script elements. A function defined in a later script element won't be available during the initial run of an earlier script element.

您需要交换脚本元素的顺序,或延迟函数调用,直到定义它的脚本运行(例如将其附加到 onload 事件处理程序。)

You either need to swap the order of your script elements, or delay the function call until after the script that defines it has run (e.g. by attaching it to an onload event handler).

<script>
    function go() {
        alert('');  
    }
</script>
<script>
    go();
</script>

<script>
    window.addEventListener("load", function () { 
        go();
    }, false);
</script>
<script>
    function go() {
        alert('');  
    }
</script>