使用JQuery打开另一个卡后关闭卡

时间:2018-03-25 11:10:27

标签: javascript jquery

我正在制作记忆游戏,用卡填充div:

var masks = ["1.jpg", "2.jpg", "3.jpg", "4.jpg", "6.jpg", "7.jpg", "8.jpg", "1.jpg", "2.jpg", "3.jpg", "4.jpg", "6.jpg", "7.jpg", "8.jpg"];

for (var i = 0; i < masks.length; i++) {
  $(".deck").append('<div  class="card"> <img class="card" src="./' + masks[i] + '"/></div>');

}
//Displaying the mask images with a for loop
$(".card").click(function() {

// Show card on click
$(this).find("img").show();

})

});

然后显示卡片,但是我想这样做,当你点击一张卡片时它会一直打开,直到你点击并打开另一张卡片,这样两者都保持打开状态,用JQuery做到这一点的最佳和正确的方法是什么?

2 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

&#13;
&#13;
var masks = ["1.jpg", "2.jpg", "3.jpg", "4.jpg", "6.jpg", "7.jpg", "8.jpg", "1.jpg", "2.jpg", "3.jpg", "4.jpg", "6.jpg", "7.jpg", "8.jpg"];

//add style style="display: none;" so that when added, images are hidden
for (var i = 0; i < masks.length; i++) {
  $(".deck").append('<div  class="card"> <img class="card" style="display: none;" src="./' + masks[i] + '"/></div>');
}

//Displaying the mask images with a for loop
$(".deck").on('click', '.card', function() {
  var cardVisible = $('.card img:visible').length;       //Get the number of visible img
  if (cardVisible >= 2) $('.card img').hide();           //If 2 or more, hide all

  $(this).find("img").show();                            //Show the image
});
&#13;
.card {
  width: 100px;
  height: 100px;
  background-color: red;
  margin: 5px;
  float : left;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='deck'></div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

&#13;
&#13;
$(function(){
  var current=null;
  var previous=null;
  var masks = [
  "http://www.iconsplace.com/icons/preview/orange/number-1-256.png",
  "http://www.iconsplace.com/icons/preview/orange/number-2-256.png",
  "http://www.iconsplace.com/icons/preview/orange/number-3-256.png",
  "http://www.iconsplace.com/icons/preview/orange/number-4-256.png",
  "http://www.iconsplace.com/icons/preview/orange/number-5-256.png",
  ];
  
  for (var i = 0; i < masks.length; i++) {
    $(".deck").append('<div  class="card"><img class="card-img" src="' + masks[i] + '"/></div>');
  }
  
  $(".card").on("click", function(){
    previous = current;
    current = $(this).find("img");
    $(".card-img").hide();
    $(previous).show();
    $(current).show();
  });
})
&#13;
.card{
  width:50px;
  height:50px;
  background-color: yellow;
  margin:3px;
  display: inline-block;
}

.card-img{
  width:48px;
  display:none;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="deck">
</div>
&#13;
&#13;
&#13;