JavaScript:追加子项

发布于 2024-11-27 09:10:26 字数 817 浏览 1 评论 0原文

我正在学习 appendChild ,到目前为止已经想出了这段代码:

var blah = "Blah!";
var t = document.createElement("table"),
  tb = document.createElement("tbody"),
  tr = document.createElement("tr"),
  td = document.createElement("td");

t.style.width = "100%";
t.style.borderCollapse = 'collapse';

td.appendChild(document.createTextNode(blah));

// note the reverse order of adding child        
tr.appendChild(td);
tb.appendChild(tr);
t.appendChild(tb);

document.getElementById("theBlah").appendChild(t);
<div id="theBlah">d</div>

但这给了我一个错误:Uncaught TypeError: Cannot call method 'appendChild' of null。我做错了什么?

I was learning about appendChild and have so far come up with this code:

var blah = "Blah!";
var t = document.createElement("table"),
  tb = document.createElement("tbody"),
  tr = document.createElement("tr"),
  td = document.createElement("td");

t.style.width = "100%";
t.style.borderCollapse = 'collapse';

td.appendChild(document.createTextNode(blah));

// note the reverse order of adding child        
tr.appendChild(td);
tb.appendChild(tr);
t.appendChild(tb);

document.getElementById("theBlah").appendChild(t);
<div id="theBlah">d</div>

But that gives me an error saying Uncaught TypeError: Cannot call method 'appendChild' of null. What am I doing wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

以往的大感动 2024-12-04 09:10:26

尝试将 JavaScript 封装在 onload 函数中。所以首先添加:

<body onload="load()">

然后将你的javascript放入加载函数中,所以:

function load() {
    var blah="Blah!";
    var t  = document.createElement("table"),
    tb = document.createElement("tbody"),
    tr = document.createElement("tr"),
    td = document.createElement("td");

    t.style.width = "100%";
    t.style.borderCollapse = 'collapse';

    td.appendChild(document.createTextNode(blah)); 

    // note the reverse order of adding child        
    tr.appendChild(td);
    tb.appendChild(tr);
    t.appendChild(tb);

   document.getElementById("theBlah").appendChild(t);
}

Try wrapping your JavaScript in an onload function. So first add:

<body onload="load()">

Then put your javascript in the load function, so:

function load() {
    var blah="Blah!";
    var t  = document.createElement("table"),
    tb = document.createElement("tbody"),
    tr = document.createElement("tr"),
    td = document.createElement("td");

    t.style.width = "100%";
    t.style.borderCollapse = 'collapse';

    td.appendChild(document.createTextNode(blah)); 

    // note the reverse order of adding child        
    tr.appendChild(td);
    tb.appendChild(tr);
    t.appendChild(tb);

   document.getElementById("theBlah").appendChild(t);
}
意犹 2024-12-04 09:10:26

该脚本在页面完成加载之前运行。这就是 document.getElementById("theBlah") 返回 null 的原因。

要么使用 jQuery 之类的东西,要么简单地使用类似的东西

<script>
window.onload = function () {
    var blah="Blah!";
    var t  = document.createElement("table"),
    tb = document.createElement("tbody"),
    ...
    //the rest of your code here
};
</script>

The script is being run before the page completes loading. Which is why document.getElementById("theBlah") returns null.

Either use something like jQuery or simply something like

<script>
window.onload = function () {
    var blah="Blah!";
    var t  = document.createElement("table"),
    tb = document.createElement("tbody"),
    ...
    //the rest of your code here
};
</script>
儭儭莪哋寶赑 2024-12-04 09:10:26

问题是 document.getElementById("theBlah") 返回 null。原因是您的代码在创建 theBlah 元素之前运行。您应该将代码放置在 onload 事件处理程序中。

The problem is that document.getElementById("theBlah") returns null. The reason why is that your code is running before the theBlah element has been created. You should place your code in an onload event handler.

寂寞清仓 2024-12-04 09:10:26

正确的方法(行和列以及随机的内部文本是动态设置的......由您)
这种方式可能不是最短的,但是是构建表格最快的方式。
它也是一个带有 thead 的完整表格,并填充了随机文本:

  1. 使用本机 JavaScript(不会减慢 JQuery)

  2. (function(){})() 在 body 加载之前执行代码

  3. 与外部的其他变量没有问题函数

  4. 并传递文档,因此变量较短

  5. 有一种方法可以缩短通过使用克隆节点来实现该功能...但速度较慢,并且可能并非所有浏览器都支持

  6. 使用createDocumentFragment()创建tr 的。如果您有很多行,这有助于更快地构建 DOM。

    (function (d) {
        var rows = 10,
            cols = 3,
            t = d.createElement('table'),
            the = d.createElement('thead'),
            tb = d.createElement('tbody'),
            tr = d.createElement('tr');
        t.style.width = "100%";
        t.style.borderCollapse = 'collapse';
        for (var a = 0; a < cols; a++) {
            var th = d.createElement('th');
            th.innerText = Math.round(Math.random() * 100);
            tr.appendChild(th);
        };
        the.appendChild(tr);
        var f = d.createDocumentFragment();
        for (var a = 0; a < rows; a++) {
            var tr = d.createElement('tr');
            for (var b = 0; b < cols; b++) {
                var td = d.createElement('td');
                td.innerText = Math.round(Math.random() * 100);
                tr.appendChild(td);
            }
            f.appendChild(tr);
        }
        tb.appendChild(f);
        t.appendChild(the);
        t.appendChild(tb);
        window.onload = function () {
            d.body.appendChild(t)
        };
    })(document)

proper way (rows & cols & the random innerText is set dynamically ...by you)
this way is probably not the shortest but by way the fastest to build a table.
It’s also a full table with thead and filled with random text:

  1. use native JavaScript (not slowing down JQuery)

  2. (function(){})() executes the code before body is loading

  3. doesn’t have problems with other variables outside the function

  4. and pass the document so you have shorter variables

  5. there is a way to shorten the function by using clone node... but it’s slower and maybe not supported by all browsers

  6. use createDocumentFragment() to create the tr’s. If you have a lot of rows this helps to build the DOM faster.

    (function (d) {
        var rows = 10,
            cols = 3,
            t = d.createElement('table'),
            the = d.createElement('thead'),
            tb = d.createElement('tbody'),
            tr = d.createElement('tr');
        t.style.width = "100%";
        t.style.borderCollapse = 'collapse';
        for (var a = 0; a < cols; a++) {
            var th = d.createElement('th');
            th.innerText = Math.round(Math.random() * 100);
            tr.appendChild(th);
        };
        the.appendChild(tr);
        var f = d.createDocumentFragment();
        for (var a = 0; a < rows; a++) {
            var tr = d.createElement('tr');
            for (var b = 0; b < cols; b++) {
                var td = d.createElement('td');
                td.innerText = Math.round(Math.random() * 100);
                tr.appendChild(td);
            }
            f.appendChild(tr);
        }
        tb.appendChild(f);
        t.appendChild(the);
        t.appendChild(tb);
        window.onload = function () {
            d.body.appendChild(t)
        };
    })(document)
朱染 2024-12-04 09:10:26

我相信你可以使用 defer 属性将 JavaScript 链接到 html。

<script src="script.js" defer></script>

这样,您的 JavaScript 才会在页面加载后运行。

I believe you can just link your JavaScript to your html using the defer attribute.

<script src="script.js" defer></script>

This way your JavaScript will not run until after the page has loaded.

讽刺将军 2024-12-04 09:10:26

请使用 JQuery,为您自己和我们一个忙。一切都变得简单多了。

$('div.SomeDiv').append($('<table></table>').css('width','100%').append($('<tbody></tbody>').append($('<tr></tr>').append($('<td></td>').html("Blah Text"))))); // Everything else you want to add here...

Do yourself and us a favor and use JQuery. Everything becomes much simpler.

$('div.SomeDiv').append($('<table></table>').css('width','100%').append($('<tbody></tbody>').append($('<tr></tr>').append($('<td></td>').html("Blah Text"))))); // Everything else you want to add here...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文