【问题标题】:Printing HTML element on console returning NULL (javascript)在返回 NULL 的控制台上打印 HTML 元素(javascript)
【发布时间】:2021-11-15 06:12:58
【问题描述】:
function test(){
  let cart1 = document.getElementById('cart1');
  console.log(cart1);
}

我创建了一个测试函数,将<p> 标记内的内容打印到控制台。

这是我的 HTML。

<body> 
  <p id="cart1">
    hello world
  </p>
  <script src="home.js"></script>
</body>
</html>

但这是在控制台上打印的内容:

为什么会这样?

【问题讨论】:

  • 您何时以及如何致电test()
  • 你怎么打电话给test? (仅供参考,如果您调用 test,您的代码就可以工作。但我很惊讶它会返回 null。)
  • 我已经执行了你的代码,我没有得到空值。 'p' 的值打印在控制台上。在您的情况下可能发生的情况是 JavaScript 代码在页面完全加载之前被执行。结果它无法找到元素,导致null。考虑更改脚本的顺序。

标签: javascript html web


【解决方案1】:

只需像这样编辑您的Home.js

function test() {
  let cart1 = document.getElementById('cart1');
  console.log(cart1);
}

test();
<p id="cart1">
  hello world
</p>

【讨论】:

  • 这并不能解释为什么控制台会记录null
  • 我还是 null
【解决方案2】:

请将您的 JS 代码替换为以下内容。您必须使用 innerHTML 属性从 p 标签中获取文本。 innerHTML 属性设置或返回元素的 HTML 内容(内部 HTML)。

test();

function test(){
  let cart1 = document.getElementById('cart1').innerHTML;
  console.log(cart1);
}

【讨论】:

  • 这会返回一个类型错误
  • textContentinnerText 会更好。
  • @DarthTensor,你最好看看这个Link。它不会返回类型错误。
  • @Andy 是的,你是对的。有很多方法可以完成一项任务。
  • @RajuAhmed 它仍然对我有用
【解决方案3】:

我无法重现这个问题,我写了一个简单的例子,它工作正常。

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
</head>
<body>
  <p id="cart1">hello world</p>
</body>
<script type="text/javascript">
    function test() {
      let cart1 = document.getElementById('cart1');
      console.log(cart1);
    }
    test();
</script>
</html>

如果他还有问题,我建议使用onload事件。

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
</head>
<body>
  <p id="cart1">hello world</p>
</body>
<script type="text/javascript">
    window.onload = () => {
       let cart1 = document.getElementById('cart1');
      console.log(cart1);
    }
</script>
</html>

【讨论】:

    【解决方案4】:

    我认为你应该做 console.log(cart1.innerHTML);

    【讨论】:

    • 我做到了...它返回一个错误
    猜你喜欢
    • 1970-01-01
    • 2015-01-26
    • 1970-01-01
    • 1970-01-01
    • 2015-03-16
    • 2012-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多