GetElementBy 仅适用于 ID 而不适用于类

使用下面的代码,我想<content>在用户单击<button>.

在我使用这段代码之前,它工作得很好。然后我JavaScript代码id="content"toclass="content"和 the更改,现在该函数不再工作了。document.getElementByIdgetElementsByClassName

我必须更改我的代码以使其也适用于类吗?

你也可以在这里找到我的代码

window.myFunction = function () {
    var x = document.getElementsByClassName("content");
    if (x.style.display === 'none') {
        x.style.display = 'block';
    } else {
        x.style.display = 'none';
    }
}
.content {
    width: 80%;
    padding: 10%
    text-align: center;
    background-color: lightblue;
    margin-top:20px;
}
<button onclick="myFunction()">Button</button>

<div class="content">
Content of element
</div>

克里斯托斯

方法 getElementsByClassName

返回具有所有给定类名称的所有子元素的类数组对象。

欲了解更多信息,请看这里因此,您必须获取数组的第一个元素,才能获得相同的结果。您可以使用索引 0 来访问它。

window.myFunction = function () {
    var x = document.getElementsByClassName("content")[0];
    if (x.style.display === 'none') {
        x.style.display = 'block';
    } else {
        x.style.display = 'none';
    }
}
.content {
    width: 80%;
    padding: 10%
    text-align: center;
    background-color: lightblue;
    margin-top:20px;
}
<button onclick="myFunction()">Button</button>

<div class="content">
Content of element
</div>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章