【问题标题】:Difference between console.log and document.getElementById()console.log 和 document.getElementById() 的区别
【发布时间】:2021-09-07 13:37:13
【问题描述】:
const arr=[1,2,3,4,5];
arr.forEach(function(val){
console.log(val);
})
Output
1
2
3
4
5
const arr=[1,2,3,4,5];
arr.forEach(function(val){
document.getElementById("demo").innerHTML=val;
})
Output
5

我的问题是为什么即使在使用相同的代码行后我得到不同的输出。

【问题讨论】:

  • 因为循环做完全不同的事情。为什么您认为登录到控制台与更新某些元素的 HTML 相同?

标签: javascript getelementbyid console.log


【解决方案1】:

在下面的代码中:

const arr=[1,2,3,4,5];
arr.forEach(function(val){
document.getElementById("demo").innerHtml=val;
})

对于每个循环,它会说带有 id demo set new innerHtml 的 html 元素。所以它将获得值 1,然后被 2、3、4、5 覆盖。最后,您的最终内部 html 将是 5。 要显示所有 arr 值,您需要将单独的元素放入如下代码:

const arr=[1,2,3,4,5];
arr.forEach(function(val){
document.getElementById("demo" + val).innerHtml=val; 
})

【讨论】:

  • 非常感谢,这就是我跳过的内容。
【解决方案2】:

Console.log 将您的输出打印到控制台。 documet.getElementById() 返回具有指定值的 Id 属性的元素。 两者完全不同。

【讨论】:

    【解决方案3】:

    console.log 方法为每个数组值打印val

    const arr=[1,2,3,4,5];
    arr.forEach(function(val){
        console.log(val);
    })
    

    但是,document.getElementById().innerHtml 会更新元素的innerHtml

    const arr=[1,2,3,4,5];
    arr.forEach(function(val){
        document.getElementById("demo").innerHtml=val;
    })
    

    在上面的代码中,您将覆盖元素innerHtml(body) 的当前值。 您需要每次将innerHtml 的当前值与val连接附加

    document.getElementById("demo").innerHTML += val;
    

    【讨论】:

      猜你喜欢
      • 2020-02-03
      • 2014-03-19
      • 2015-11-05
      • 2012-02-21
      • 2016-06-11
      • 2017-06-07
      • 1970-01-01
      • 2018-03-26
      • 2023-03-22
      相关资源
      最近更新 更多