jQuery切換事件


有html頁面內容如下:
<body>
<h5 id="hh">關於jQuery的介紹</h5>
<p id="p1">jQuery是一門前端編程語言</p>
</body>

需要實現點擊標題顯示和隱藏段落的功能。

第一種通過點擊方法實現,代碼如下,需要注意is(":visible")的使用

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <script src="../script/jquery-2.1.4.js"></script>
    <title></title>
    <script>
        $(function(){
            $("#hh").click(function(){
               if($(this).next().is(":visible")){
                   $(this).next().hide();
               }
                else{
                   $(this).next().show();
               }
            });
        });
    </script>
</head>
<body>
<h5 id="hh">關於jQuery的介紹</h5>
<p id="p1">jQuery是一門前端編程語言</p>
</body>
</html>

第二種方法通過toggle使用,當toggle代碼如下時,效果是先出現一段文字

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <script src="../script/jquery-2.1.4.js"></script>
    <title>toggle</title>
    <script>
    $(function(){
        $("#hh").toggle(function(){
            $(this).next().show();
        },function(){
            $(this).next().hide();
        })
    })
    </script>
</head>
<body>
<h5 id="hh">關於jQuery的介紹</h5>
<p id="p1">jQuery是一門前端編程語言</p>
</body>
</html>

而要實現點擊切換的效果,新的jQuery代碼應該是:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <script src="../script/jquery-2.1.4.js"></script>
    <title>toggle</title>
    <script>
        $(function(){
            $("#hh").click(function(){
                $(this).next().toggle(600);
            },function(){
                $(this).next().toggle(600);
            })
        })
    </script>
</head>
<body>
<h5 id="hh">關於jQuery的介紹</h5>
<p id="p1">jQuery是一門前端編程語言</p>
</body>
</html>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM