javascript - 当我在函数上使用 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>
该代码不显示任何按钮。当相同的代码在函数外部时,这是可行的,但是当我在函数内添加此代码时,这不起作用。
我该如何解决?
解决方案
当 DOM 准备好时,您必须调用您的函数。
<script>window.onload = prueba;</script>
推荐阅读
- azure - 通过 arm 的 Azure 恢复保管库备份策略不会更改时区
- scala - 如何在 scala Trait 的方法中添加通用代码
- c - qsort() 不对数组排序
- sql - 如何在学生表中添加一列。参考以下模式并在学生表中添加一个字段 - Age Number(2)
- excel - 搜索列标题从右到左 vba
- c# - Microsoft Visual Studio 2017 SUS 不突出着色器语法
- reactjs - 在循环中使用 setState
- mysql - 通过查询选择多个组中的最高计数
- c - 来自 getchar() 的输入出现问题,保存到变量的值不正确
- html - 当您启动快速服务器时,本地存储的图像是否会停止在文档上呈现?