JavaScript函数和按钮

时间:2018-02-08 12:41:42

标签: 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>

出于某种原因,我不明白这两个功能同时不起作用,但只能单独使用。

非常感谢你!

2 个答案:

答案 0 :(得分:3)

您的代码中有2个错误

  1. myFunction2中,您拼错了getElementByID =&gt;它是getElementById
  2. myFunction2中,您拼错了background-color =&gt;它是backgroundColor
  3. &#34;连字符&#34;属性或函数的名称不允许使用。

    更正后,您的代码效果很好。这是片段。

    &#13;
    &#13;
    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";
    }
    &#13;
    <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>
    
    </body>
    &#13;
    &#13;
    &#13;

答案 1 :(得分:3)

myFunction2

中有拼写错误
getElementById
             ^ small letter

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

&#13;
&#13;
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";
}
&#13;
<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>
&#13;
&#13;
&#13;