为什么在 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/