gpt4 book ai didi

javascript - 使用 Javascript 更改类的内容

转载 作者:技术小花猫 更新时间:2023-10-29 12:36:57 27 4
gpt4 key购买 nike

我开始阅读 W3schools 中的 JavaScript 并测试/更改他们提供的示例中的一些内容,这样我就可以看到正在做什么,但还没有设法识别语法。

下面是改变p标签内容的原始代码,link

<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>

我想知道如何更改同一个类的内容,但失败了,因为您可以看到下面的示例不起作用。 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"是一个可以是其他任何东西的变量还是一个命令?

最佳答案

您的 x - 是元素数组。尝试使用循环:

<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>

参见 FIDDLE

关于javascript - 使用 Javascript 更改类的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21813122/

27 4 0
文章推荐: android - 我的 galaxy note 的 cpuinfo
文章推荐: jquery - 嵌入在 标签中的 PDF 未在 IE 11 中加载