我是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>
出于某种原因,我不明白这两个功能同时不起作用,但只能单独使用。
非常感谢你!
答案 0 :(得分:3)
您的代码中有2个错误
myFunction2
中,您拼错了getElementByID
=&gt;它是getElementById
。myFunction2
中,您拼错了background-color
=&gt;它是backgroundColor
。&#34;连字符&#34;属性或函数的名称不允许使用。
更正后,您的代码效果很好。这是片段。
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;
答案 1 :(得分:3)
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";
}
&#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;