gpt4 book ai didi

javascript - 使用 onclick 命令隐藏 DIV 元素

转载 作者:行者123 更新时间:2023-11-29 18:04:22 25 4
gpt4 key购买 nike

感谢所有帮助我解决此问题的人。

所以问题是我正在尝试使用按钮隐藏带有 onclick 事件的元素(按类)。但是我做不到。

这是jsfiddle上的代码 http://jsfiddle.net/1tpdgrnj/

这里是那些希望在这里帮助我的人的代码:

HTML:

<div class="box">Hide on button click!!
<button onclick="close();">Close</button>

Javascript:

function close() {
document.getElementsByClassName("box").style.display = 'none';}

更新

请参阅下面的答案和 jsfiddle,看看它有何不同。

最佳答案

看这个fiddle

按如下方式更改您的 javascript

function myFunction() {
document.getElementsByClassName("box")[0].style.display = 'none';
}

首先应该做的更改是,重命名您的函数名称,因为 close 是 Javascript 中的关键字。

第二个是,document.getElementsByClassName() 返回一个数组,因此要获取第一个元素,您应该使用索引位置 0

根据docs

The Element.getElementsByClassName() method returns a live HTMLCollection containing all child elements which have all of the given class names. When called on the document object, the complete document is searched, including the root node.

阅读更多相关信息 here

关于javascript - 使用 onclick 命令隐藏 DIV 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32464951/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com