jquery - 为什么我的新类(class)没有被录取?

标签 jquery css html

我正在尝试更改按钮的类,因此当单击按钮时,它会隐藏一个 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 和 Chrome 开发工具确认)。但是当我再次点击它时,什么也没有发生..

如有任何帮助,我们将不胜感激!

最佳答案

您可以使用 delegate当你动态改变html时。看这个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");
});

关于jquery - 为什么我的新类(class)没有被录取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14801520/

相关文章:

javascript - 如何使用jquery删除ul列表中的空li?

javascript - 导航到无序列表中的上层列表元素

html - 在两个 div 之间创建一个滚动 div

javascript - 将颜色更改为不同的 php 结果

javascript - 引用动态加载的元素

javascript - 通过包含字符串的名称获取对象索引

javascript - javascript 错误,可能是语法?

css - sass : $someName: <%= someName %> 这个表达式是什么意思

html - 将 <h1> 标签放在 Angular 落

html - 强制移动浏览器以其原始分辨率显示网页