0

jQuery での html タグのクラスの切り替えについて質問がありました

今、私は次のようなコードを持っています

<body>
    <button id="login" class="login">login</button>


    <script>
        jQuery(function($){

            $('.logout').click(function(){
                $(this).removeClass('logout');
                $(this).addClass('login');
                $(this).text('login');
                alert('logged out, ready to login');
            });

            $('.login').click(function(){
                $(this).removeClass('login');
                $(this).addClass('logout');
                $(this).text('logout');
                alert('logged in, ready to logout');
            });

        });
    </script>
</body>

どのクラスであっても $('.login').click を常に実行するのはなぜだろうか。

ありがとう

4

6 に答える 6

0

これは良い方法です

$(document).on('click', '.login, .logout', function(){
    var current = this.className.match(/login|logout/)[0];
        // Detect the current button name & class ^ 

        opposite = current === 'login' ? 'logout' : 'login';
        // Get the opposite name & class ^ 

   $('.' + opposite).toggleClass('login logout').text(current);
   // Change the opposite ^ 

   $(this).toggleClass('login logout').text(opposite);
   // Change the Current ^

});

デモ

于 2013-07-18T18:16:21.133 に答える