【问题标题】:jQuery - Getting a reset button to workjQuery - 让重置按钮工作
【发布时间】:2014-03-05 09:51:17
【问题描述】:

我正在编写一个基本的记忆游戏,您可以在其中翻转 2 张卡片,如果它们不匹配,它们就会翻转回来,但如果它们匹配,它们的背景颜色就会发生变化。我想要一个按钮,可以随时将游戏重置为所有空白卡,无论是在游戏进行中还是在游戏结束时。

代码如下:

<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>Matching Game</title>
<!-- <link href="style.css" rel="stylesheet"> -->
<style type="text/css">
* {
    margin: 0;
    padding: 0;
}
body {
    font-family: futura;
}
h2 {
    text-align: center;
}
ul {
    width: 428px;
    margin: 0 auto;
    padding: 0;
}
ul li {
    float: left;
    width: 100px;
    border: 1px solid #444;
    list-style: none;
    padding: 70px 0;
    margin: 0 5px 5px 0;
    text-align: center;
    color: #fff;
    font-weight: bold;
    border-radius: 1em;
}
ul li:hover {
    border: 1px solid red;
}
ul li.flipped {
    color: #444;
}
.clearfix {
clear: both;
}
</style>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
</head>
<body>

<h2>Click two different cards to see if they match!</h2>
<ul>
    <li>salmon</li>
    <li>swordfish</li>
    <li>swordfish</li>
    <li>shrimp</li>
    <li>lobster</li>
    <li>scallops</li>
    <li>lobster</li>
    <li>salmon</li>
    <li>tuna</li>
    <li>scallops</li>
    <li>tuna</li>
    <li>shrimp</li>
</ul>

<div class="clearfix"></div>
<p><button type="reset" value="Reset">Reset</button></p>

<script type="text/javascript">

$(function() {
    var firstCard = null;

    $('li').on('click', function(e) {
        e.preventDefault();

        $(this).addClass('flipped');

        if (firstCard === null) {
            firstCard = $(this);
        } else {
            if (firstCard.text() === $(this).text()) {
                firstCard = null;
            } else {
                var secondCard = this;

                setTimeout(function() {
                    firstCard.removeClass('flipped');
                    $(secondCard).removeClass('flipped');

                    firstCard = null;
                }, 1000);
            }
        }
    });
});
</script>
</body>
</html>

【问题讨论】:

  • 问题是什么?
  • 我把标题搞砸了;问题是如何获得重置卡片的按钮。对此感到抱歉。

标签: jquery css class button reset


【解决方案1】:

根据您的问题,听起来您只需要删除所有 flipped 类:

$('.flipped').removeClass('flipped');

【讨论】:

    【解决方案2】:

    将此添加到您的确认功能:

    firstCard.css({backgroundColor: 'green'});
    $(this).css({backgroundColor: 'green'});
    

    为了您的重置:

    $('#reset').on('click', function(){
            $('li').removeClass('flipped').removeAttr('style');
        });
    

    见我的fiddle

    【讨论】:

      猜你喜欢
      • 2021-10-21
      • 1970-01-01
      • 1970-01-01
      • 2020-06-14
      • 2017-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多