为什么我的新课程没有被选中?

时间:2013-02-10 19:10:36

标签: jquery css html5

我正在尝试更改按钮的类,因此当它单击时,它隐藏了一个div,文本更改为显示并且使用addClass / removeClass更改类,因此可以通过下一个单击事件拾取它。将扭转这一进程。

然而,它不太有效,我不确定原因:/

继承我的代码。

HTML:

<!DOCTYPE html>
<html>
    <head>
        <title>Vanishing Act</title>
        <link rel='stylesheet' type='text/css' href='stylesheet.css'/>
        <script type='text/javascript' src='script.js'></script>
    </head>
    <body>
        <div class="vanish1"></div>
        <div class="vanish2"></div>
        <div class="vanish3"></div>
        <div class="vanish4"></div>
        <br/>
        <br />
        <button class='first' value='button'>Hide the box!</button>
    </body>
</html>

CSS:

.vanish1 {
    height: 100px;
    width: 100px;
    display: inline-block;
    background-color: #F38630;
    border-radius: 5px;
}

.hide1 {
    color: red;
}

JQ:

    $(document).ready(function() {
    $('.first').click(function() {
            $('.vanish1').fadeOut('slow');
            $(this).text('Show the box!');
            $(this).addClass("hide1");
            $(this).removeClass("first");
    });

    $('.hide1').click(function() {
        $('.vanish1').fadeIn('slow');
        $(this).text('Hide the box!');
        $(this).removeClass("hide1");
        $(this).addClass("first");
    });
});

当我单击按钮时,div成功隐藏并更改了类(由CSS和Chromes开发工具确认)。但当我再次点击它时,没有任何反应..

任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:5)

当您动态更改html时,可以使用delegate。见Fiddle

$('body').on('click', '.first', function() {
        $('.vanish1').fadeOut('slow');
        $(this).text('Show the box!');
        $(this).addClass("hide1");
        $(this).removeClass("first");
});
$('body').on('click', '.hide1', function() {
    $('.vanish1').fadeIn('slow');
    $(this).text('Hide the box!');
    $(this).removeClass("hide1");
    $(this).addClass("first");
});

答案 1 :(得分:-1)

在定义处理程序时,.hide1按钮尚不存在,因此它不会绑定事件。有两种方法:

1:使用实际切换:

(function() {
    var toggle = true;
    $(document).ready(function() {
        $(".first").click(function() {
            toggle = !toggle;
            if( toggle) {
                $(".vanish1").fadeIn("slow");
                $(this).text("Hide the box!").removeClass("hide1").addClass("first");
            }
            else {
                $(".vanish1").fadeOut("slow");
                $(this).text("Show the box!").addClass("hide1").removeClass("first");
            }
        });
    });
})();

或2:使用on

$(document).ready(function() {
    $('.first').on('click',function() {
            $('.vanish1').fadeOut('slow');
            $(this).text('Show the box!').addClass("hide1").removeClass("first");
    });

    $('.hide1').on('click',function() {
        $('.vanish1').fadeIn('slow');
        $(this).text('Hide the box!').removeClass("hide1").addClass("first");
    });
});

方法1是首选。

相关问题