Я не могу установить правильный эффект переключения на кнопку с классом начальной загрузки - PullRequest
0 голосов
/ 16 октября 2019

В последнее время я начал изучать jquery, и вот что я пытаюсь сделать: я добавил событие нажатия кнопки селектора (по имени тега), просто чтобы выполнить простое переключение текста и класса.

Текстовая часть работает нормально, используя условное выражение, но если я попытаюсь переключить класс между btn-danger и btn-success, я не смогу правильно установить его и не смог понять, что изменить.

<html>
    <head>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" 
        integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" 
        crossorigin="anonymous">
    </head>
    <body>
        <div id="outer">
            <div id="inner">
                <h4>Topic Heading</h4>
                <p>This is the first paragraph in the topic.</p>
                <p>This is the second paragraph in the topic.</p>
            </div>
            <button class="btn btn-danger">Hide</button>
        </div>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
        <script>
            $(document).ready(function (){
                $("button").click(function (){
                    $("#inner").toggle("slow");
                    if ($(this).text() == "Hide") {
                        $(this).toggleClass("btn btn-success");
                        $(this).text("Show");
                    } 
                    else { 
                        $(this).text("Hide"); 
                    };
                });
            });
        </script>
    </body>
</html>

Цвет кнопки остается красным, но выглядит совершенно иначе

Ответы [ 2 ]

2 голосов
/ 16 октября 2019

в операторе if замените ваш код на: $ (this) .addClass ("btn-success"). RemoveClass ('btn-danger');в другом случае $ (this) .addClass ('btn-danger');

<html>
    <head>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" 
        integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" 
        crossorigin="anonymous">
    </head>
    <body>
        <div id="outer">
            <div id="inner">
                <h4>Topic Heading</h4>
                <p>This is the first paragraph in the topic.</p>
                <p>This is the second paragraph in the topic.</p>
            </div>
            <button class="btn btn-danger">Hide</button>
        </div>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
        <script>
            $(document).ready(function (){
                $("button").click(function (){
                    $("#inner").toggle("slow");
                    if ($(this).text() == "Hide") {
                        $(this).addClass("btn-success").removeClass('btn-danger');
                        $(this).text("Show");
                    } 
                    else { 
                        $(this).text("Hide"); 
                        $(this).addClass('btn-danger');
                    };
                });
            });
        </script>
    </body>
</html>
2 голосов
/ 16 октября 2019

небольшое изменение вашего $(this).toggleClass("btn btn-success");

<html>
    <head>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" 
        integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" 
        crossorigin="anonymous">
    </head>
    <body>
        <div id="outer">
            <div id="inner">
                <h4>Topic Heading</h4>
                <p>This is the first paragraph in the topic.</p>
                <p>This is the second paragraph in the topic.</p>
            </div>
            <button class="btn btn-danger">Hide</button>
        </div>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script>
            $(document).ready(function (){
                $("button").click(function (){
                    $("#inner").toggle("slow");
                    if ($(this).text() == "Hide") {
                        $(this).addClass("btn-success").removeClass("btn-danger");
                        $(this).text("Show");
                    } 
                    else { 
                        $(this).addClass("btn-danger").removeClass("btn-success");
                        $(this).text("Hide"); 
                    };
                });
            });
        </script>
    </body>
</html>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...