元素设置为display:none,其绑定的事件仍存在

时间:2023-03-09 23:29:29
元素设置为display:none,其绑定的事件仍存在

 该文章在2020年1月份进行了重写,文章地址: html元素设置display为none,绑定的事件还存在么

----------------------------------------------------------------------------------------------------------------------------------------------------------

以下是2016年的旧文

元素设置为display:none,虽然该元素从页面中消失了,其绑定的事件仍存在。

  

<body>
<button class="button1">change1</button>
<button class="button2">change2</button>
<button class="button3">change3</button>
<div class="test" style="width:50px;height:50px;background-color: red;"></div>
<script>
$(function () {
$('.button1').toggle(function() {
$('.test').css('background-color', 'black');
},function () {
$('.test').css('background-color', 'red');
});
$('.button2').click(function() {
$('.test').hide();
});
$('.button3').click(function() {
$('.test').show();
});
})
</script>
</body>

元素设置为display:none,其绑定的事件仍存在

上图是初始页面。change1可以使div在红色和黑色切换,当点击change2时,div消失,然后点击change1,那这次点击能否是消失的div颜色变化呢?揭晓答案,最后,我们点击change3使div出现,发现消失的div颜色变了。所以结论是,元素设置为display:none,其绑定的事件仍存在。