首页 > 调用toggle()方法的元素为什么会自动消失?

调用toggle()方法的元素为什么会自动消失?

test.html的代码如下:

<html>
<head>
    <script type="text/javascript" src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
    <style type="text/css">
        .bi{
            background-color: blue
        }
    </style>
</head>
<body>
    <div>
        <button id="btn" style="display:block">click</button>
    </div>
    <div id="div2" style="height:200px;width:200px;border:1px solid red">
    </div>
<script type="text/javascript">
$(function(){
    $("#btn").toggle(function(){
        $("#div2").addClass("bi");
    },function(){
        $("#div2").removeClass("bi");
    }
    );
});
</script>
</body>
</html>

在浏览器中打开test.html时,id是btn的元素会自动消失,toggle()中的函数自动调用完成,这是为什么?


因为你的jquery是用一个立即执行的函数表达式包括的,就是自动立即执行。

toggle()方法好像已经改了,改成只是单纯切换display的block或none。

这个是jquery官网给出的解释:

Description: Display or hide the matched elements.


toggle本来就是控制显示隐藏的,如果你的元素初始的是显示,这个时候执行toggle方法就自然隐藏掉了,很正常啊

【热门文章】
【热门文章】