首页 > 解决方案 > 当我在函数上使用 javascript 代码时,它不起作用

问题描述

我开始使用javascript,我的问题是:我有这段代码,可以正常工作:

<table class="table table-striped table-bordered table-list" id="table">
    <tbody id="tbody">
        <script>
            var btn = document.createElement("BUTTON");// Create a <button> element
            btn.setAttribute('type', 'button'); // input element of type button
            btn.setAttribute('value', 'prueba');
            btn.setAttribute('id', 0);

            var t = document.createTextNode("prueba");       // Create a text node
            btn.appendChild(t);                                // Append the text to <button>
            document.body.appendChild(btn);
        </script>
    </tbody>
</table>

但我需要在同一页面上多次使用它。所以我尝试将它添加到一个函数上,如下所示:

<script>
   function prueba(){

        var btn = document.createElement("BUTTON");
        .......
        document.body.appendChild(btn);
   };
</script>

问题是当我调用这个函数时:

<script>prueba();</script>

该代码不显示任何按钮。当相同的代码在函数外部时,这是可行的,但是当我在函数内添加此代码时,这不起作用。

我该如何解决?

标签: javascriptfunction

解决方案


当 DOM 准备好时,您必须调用您的函数。

<script>window.onload = prueba;</script>

推荐阅读