我不知道 var 的范围 [英] I don't know the scope of var

查看:46
本文介绍了我不知道 var 的范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用vanilla js做一张桌子.但是根据我声明 var 的位置,我得到了不同的结果.

I want to make a table with vanilla js. But I got a different result depending on where I declare the var.

var body = document.body;
var table = document.createElement('table');
var tr = document.createElement('tr');
var td = document.createElement('td');
body.appendChild(table);
for (var i = 0; i < 3; i +=1) {
    
    table.appendChild(tr);
    for (var j = 0; j < 3; j+=1) {
        
        tr.appendChild(td);
        td.textContent = 'td';
    }
}

我想做 3*3 的桌子.但它做了1*1的桌子.

I wanted to make 3*3 table. But it made 1*1 table.

var body = document.body;
var table = document.createElement('table');
body.appendChild(table);
for (var i = 0; i < 3; i +=1) {
    var tr = document.createElement('tr');
    table.appendChild(tr);
    for (var j = 0; j < 3; j+=1) {
        var td = document.createElement('td');
        td.textContent = 'td';
        tr.appendChild(td);
    }
}

并且它成功地工作了.有什么区别?

And it was successfully worked. What is difference?

推荐答案

查看 appendChild:

Node.appendChild() 方法将一个节点添加到指定父节点的子节点列表的末尾.如果给定的子节点是对文档中现有节点的引用,则 appendChild() 会将其从当前位置移动到新位置.

The Node.appendChild() method adds a node to the end of the list of children of a specified parent node. If the given child is a reference to an existing node in the document, appendChild() moves it from its current position to the new position.

在你的第一个代码中,你创建了 one trone td,然后在循环中,在每次迭代中,您从之前的位置删除 trtd,然后再添加它们.

In your first code, you create one tr and one td, and then in the loops, on each iteration, you remove the tr and td from their previous locations before appending them again.

相反,在您的第二个代码中,您在每次迭代时都调用 createElement,因此 tdtr 的新元素变量保持在被追加之前不存在于文档中,所以没有被删除,结果生成了 3x3 网格.

In contrast, in your second code, you're calling createElement on every iteration, so the new elements that the td and tr variables hold do not exist in the document before being appended, so nothing gets removed, and the 3x3 grid gets produced as a result.

它实际上与作用域没有任何关系 - 它与您使用 createElement 创建新元素而不是重复使用您附加到之前的迭代.

It doesn't really have anything to do with scope - it has to do with the fact that you're creating new elements with createElement instead of re-using the same element you appended in a prior iteration.

这篇关于我不知道 var 的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆