JavaScript 函数和按钮

标签 javascript html css

<分区>

我是 JavaScript 的初学者。我一直在尝试使用以下两个应该由单击按钮触发的函数来更改 HTML 内容:

<body>

  <p id="demo">This is a demonstration.</p>
  <button onclick="myFunction()">Click Me!</button>

  <p id="demo2">JavaScript can change the style of an HTML element.</p>
  <button onclick="myFunction2()">Click me!</button>


  <script>
  function myFunction() {
      document.getElementById("demo").innerHTML = "Hello JavaScript!";
  }

  function myFunction2(){
      document.getElementByID("demo2").style.fontSize="25px";
      document.getElementByID("demo2").style.color="red";
      document.getElementByID("demo2").style.background-color="yellow";
  }
  </script>

</body>

出于某种原因,我不明白这两个功能不能同时工作,而是分开工作。

非常感谢您!

最佳答案

你在 myFunction2 中有错字

getElementById
             ^ small letter

document.getElementById("demo2").style.backgroundColor = "yellow";
                                       ^^^^^^^^^^^^^^^ a single property with capital
                                                       letter instead of dash

function myFunction() {
    document.getElementById("demo").innerHTML = "Hello JavaScript!";
}

function myFunction2() {
    document.getElementById("demo2").style.fontSize = "25px";
    document.getElementById("demo2").style.color = "red";
    document.getElementById("demo2").style.backgroundColor = "yellow";
}
<p id="demo">This is a demonstration.</p>
<button onclick="myFunction()">Click Me!</button>

<p id="demo2">JavaScript can change the style of an HTML element.</p>
<button onclick="myFunction2()">Click me!</button>

关于JavaScript 函数和按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48685798/

相关文章:

javascript - 在 Angular 身份验证中显示当前用户名

html - Bootstrap 颜色范围格式

javascript - 如何从div[html+jquery]获取文本

css - 如何使用css获取当前年份?

html - 在移动调整大小时将 div 中的元素锁定到位

php - 谁添加 "_"单下划线查询参数?

javascript - 为什么我运行代码时不显示数字、正方形和立方体?

javascript - Parse.com [Javascript API] : Get an array of parse objects

javascript - jQuery css 函数不适用于 svg 圆形元素

jquery - 使用 jQuery 检测 HTML5 的自动对焦功能