Body.onLoad似乎执行得太早

时间:2017-04-28 17:38:38

标签: javascript html5

编辑:抱歉,问题不同 - 它应该是<textarea id="txtScene">   而不是<textarea name="txtScene">

<body onLoad="init();">似乎在创建init();内的所有HTML竞争之前执行body

我特别喜欢这个HTML:

<script src="/home/prokop/Dropbox/MyDevSW/javascript/WebGL/shader_builder/GLSLscreen.js"></script>
<body onLoad="init_GLSLScreen();">
    <textarea name="txtScene" cols="60" rows="20" onChange="updateShader(this)">
        vec4 scene( Ray ray ){
            vec4 hit = vec4( POSITIVE_INF, vec3(0.0) );
            Sphere SURF1 = Sphere( vec3(0.0,0.0,0.0), 1.0 );
            Sphere SURF2 = Sphere( vec3(1.0,0.0,0.0), 0.75 );
            Sphere SURF3 = Sphere( vec3(0.0,1.0,0.0), 0.75 );
            vec2 ts1;
            ADD( SURF1 );
            SUB( SURF2 );
            SUB( SURF3 );
            return hit;
        } 
    </textarea>
</body>

init_GLSLScreen()内部我需要以updateShader作为参数运行textarea name="txtScene"。喜欢这个

function init_GLSLScreen(){
    // ... some stuff ... don't care
    console.log ( document.getElementById("txtScene") );
    updateShader( document.getElementById("txtScene") );
    // ... some stuff ... don't care
}

document.getElementById("txtScene")会返回null

问题描述here解决方案是将javascript移动到HTML下面(我想我的情况下不可能)或运行javascript onLoad ...我这样做但不起作用

重现此行为的条带化代码(如果您查看Web控制台)

<!DOCTYPE html>
<html>
<head>
    <title>05.10 - Custom fragment shader</title>
    <style>
        body { margin: 0; overflow: hidden; }
    </style>
</head>
<script>
     function init_GLSLScreen(){
        console.log ( document.getElementById("txtScene") );
        console.log ( document.getElementById("txtScene").value );
    }
</script>
    <body>
        <textarea name="txtScene" cols="60" rows="20" onChange="updateShader(this)">
            sfsdjfskldjflj
        </textarea>
    </body>
    <script>
     init_GLSLScreen();
    </script>
</html>

2 个答案:

答案 0 :(得分:1)

您总是可以将函数执行移动到html的底部,就在关闭正文标记之前。这将确保所有内容都加载到DOM中。

<script>
   init_GLSLScreen();
</script>

答案 1 :(得分:0)

如果您可以添加jquery,那么将代码包装在SET @var = IF ((SELECT true FROM information_schema.TABLE_CONSTRAINTS WHERE TABLE_SCHEMA = 'your_database_name' AND TABLE_NAME = 'results' AND CONSTRAINT_NAME = 'fk_results_pgrfas' AND CONSTRAINT_TYPE = 'FOREIGN KEY'), 'alter table results drop foreign key fk_results_pgrfas', 'select 1'); PREPARE stmt FROM @var; EXECUTE stmt; DEALLOCATE PREPARE stmt; 中请参阅:https://learn.jquery.com/using-jquery-core/document-ready/

如果您不想包含jquery,那么我会在jquery中获得组成.ready函数源的javascript,这样就可以复制相同的功能。

请点击此处查看计划:$(document).ready() source

如果你想使用jquery,你可以这样做:

$(document).ready(function() {});