为什么在中单击按钮时display = "none"
不起作用?
HTML:
JavaScript:
<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/>
最佳答案
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" />
在Pure 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" />