使用 Javascript 更改课程内容 [英] Changing content of class using Javascript
问题描述
我开始在 W3schools 中阅读 JavaScript 并测试/更改他们给出的示例中的一些内容,以便我可以看到什么在做什么,但还没有设法识别语法.
I started reading JavaScript in W3schools and testing out/changing few things in the examples they give so I can see what is doing what but didn't manage to identify the syntax, yet.
下面是改变p标签内容的原始代码,链接.
Below is the original code to change p tag content, the link to it.
<p id="demo">
JavaScript can change the content of an HTML element.
</p>
<script>
function myFunction()
{
x = document.getElementById("demo"); // Find the element
x.innerHTML = "Hello JavaScript!"; // Change the content
}
</script>
<button type="button" onclick="myFunction()">Click Me!</button>
我想知道如何更改同一个类的内容,但失败了,因为您可以看到下面的示例不起作用.下面的代码.
I want to know how to change contents with the same class, but failed as you can see that the example below doesn't work. Fiddle of code below.
<p class="demo">
JavaScript can change the content of an HTML element.
</p>
<p class="demo">Yolo</p>
<script>
function myFunction()
{
x = document.getElementsByClassName("demo"); // Find the element
x.innerHTML = "Hello JavaScript!"; // Change the content
}
</script>
<button type="button" onclick="myFunction()">Click Me!</button>
如果你能告诉我如何 ^^" 并帮助我理解,getElementById"是一个可以是其他任何东西的变量还是一个命令?
If you could show me how ^^" and help me understand, is "getElementById" a variable that could be anything else or is it a command?
推荐答案
你的 x - 是元素数组.尝试使用循环:
Your x - is array of elements. try to use loop:
<body>
<p class="demo">JavaScript can change the content of an HTML element.</p>
<p class="demo">Yolo</p>
<button type="button" onclick="myFunction()">Click Me!</button>
<script>
function myFunction()
{
x=document.getElementsByClassName("demo"); // Find the elements
for(var i = 0; i < x.length; i++){
x[i].innerText="Hello JavaScript!"; // Change the content
}
}
</script>
</body>
这篇关于使用 Javascript 更改课程内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!