javascript - 单击按钮时元素未隐藏

标签 javascript jquery css

为什么在 jsFiddle 中单击按钮时 display = "none" 不起作用?

HTML:

<div>This is a visible heading<div>
<div class="hidden">This is a hidden heading</div>
<div>Notice that the hidden heading still takes up space.</div>

<hr/>

JavaScript:

$('input[type=button]').click( function() {
 document.getElementsByClassName("hidden").style.display = "none";
});

最佳答案

document.getElementsByClassName() 返回 HTMLCollection这是一个类似数组的对象。您正在尝试在此数组上应用 HTML 节点属性。

首先从该数组中选择 DOM 节点,然后应用样式属性,如下所示。

document.getElementsByClassName("hidden")[0].style.display = "none";

$('input[type=button]').click( function() {
 document.getElementsByClassName("hidden")[0].style.display = "none";
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>This is a visible heading<div>
<div class="hidden">This is a hidden heading</div>
<div>Notice that the hidden heading still takes up space.</div>

<hr/>

<input type="button" value="test" />

或者,您可以使用 jQuery 来隐藏元素。

$('input[type=button]').click(function() {
  $(".hidden").first().hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>This is a visible heading<div>
  <div class="hidden">This is a hidden heading</div>
  <div>Notice that the hidden heading still takes up space.</div>

  <hr/>

  <input type="button" value="test" />

在纯 JavaScript 中,您可以按如下方式进行:

var button = document.getElementsByClassName('button')[0];

button.addEventListener('click', function() {
 document.getElementsByClassName("hidden")[0].style.display = "none";
}, false);
<div>This is a visible heading<div>
<div class="hidden">This is a hidden heading</div>
<div>Notice that the hidden heading still takes up space.</div>

<hr/>

<input class="button" type="button" value="test" />

关于javascript - 单击按钮时元素未隐藏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38611938/

相关文章:

php - 如何使用php将照片上传到数据库和文件夹中

javascript - 是否可以解析如下所示的 JSON 日期?

javascript - 鼠标进入/鼠标离开子菜单不稳定

javascript - HTML和CSS img是相连的怎么分开?

javascript - 按钮背景颜色不起作用

javascript - Javascript 中哪些类型的 block 会创建闭包

javascript - 使用 Lodash 将元素推送到对象中的任何位置

jquery - .sort 在 IE (IE 9) 中不起作用

javascript - 调整此 javascript 以与 li 和 tr 一起使用

javascript - 随机应用于元素的 jQuery 动画函数