简体   繁体   English

无法在JS中将属性'innerHTML'设置为null

[英]Cannot set property 'innerHTML' of null in JS

Code didn't work and still return 'f' world after function call, what's wrong with my code? 代码不起作用,并且在函数调用后仍然返回“ f”世界,我的代码怎么了? thanks for help 感谢帮助

HTML: HTML:

<html>
  <head>
    <script type="text/javascript" src="functions.js"></script>
  </head>
  <body onload="changeText()">
    <p id="P1">
      fu
    </p>
  </body>
</html>

JS: JS:

function changeText(){
  document.getElementById("p1").innerHTML = "slm"
}

Because the selector is case sensitive. 因为选择器区分大小写。 Try to use P1 instead of p1: document.getElementById("P1").innerHTML = "slm" 尝试使用P1代替p1: document.getElementById("P1").innerHTML = "slm"

ID's in Javascript are case sensitive (all attributes are). Javascript中的ID区分大小写(所有属性都是)。 The ID in the HTML is P1 but you're looking for p1 so it's not finding it. HTML中的ID是P1但您正在查找p1因此找不到它。

您输入的ID错误。注意P是大写字母,请尝试:

document.getElementById("P1").innerHTML = "slm"

please try this one, problem was that you can't call function changeText() : 请尝试这个,问题是您不能调用function changeText()

<html>

  <head>
    <script type="text/javascript">
      function changeText(){
        document.getElementById("P1").innerHTML = "slm"
      }
    </script>
  </head>

  <body onload="changeText()">
    <p id="P1">fu</p>
  </body>

</html>

fiddle 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM