如何用JavaScript索引HTMLdiv类?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (105)

我试图使用data属性比较不同div类的两个值,有这样的两个div类,都有不同的数据 - 值:

<div class="card" data-value=38>
    <img class ="front-face" src= "PNG/QH.png"/>
  </div>

  <div class="card" data-value=39>
    <img class ="front-face" src= "PNG/KH.png"/>
  </div>

每个div类也将使用cards.style.order接收一个唯一的订单

在JS功能中,用户将选择两张卡(firstCard,secondCard),该功能应检查firstCard的值是否大于卡的值,其顺序比secondCard高1。

这是我一直在尝试使用的代码:

const cards = document.querySelectorAll('.card');

if(firstCard.dataset.value === cards[cards.indexOf(secondCard)-1].dataset.value)

cards是一个包含所有div类的数组。我收到的一个错误告诉我indexOf在这里不是一个可用的函数。我认为这可能是因为div类实际上并不是数组的一部分,我需要一种不同的方法来找到'值'而不是'索引'。

例如,如果一排卡片分为2D,7S,9D,8H,3D,则用户可以单击3D获取firstCard,单击7S获取secondCard。该功能将验证3D的值是否大于2D并且将交换3D和7S的位置

提问于
用户回答回答于

我制作了带有自动生成方块的小片段,可以按照您的建议移动

let cardsArray = [{
  "value": 7,
  "color": "red"
 }, {
   "value": 6,
   "color": "yellow"
 }, {
   "value": 5,
   "color": "green"
 }, {
   "value": 4,
   "color": "red"
 }, {
   "value": 3,
   "color":  "yellow"
 }, {
   "value": 2,
   "color": "green"
 }, {
   "value": 1,
   "color": "green"
}]

// Function to automatically generate some squares
function drawSquares() {
  let squaresParent = $("#squaresParent");
  squaresParent.empty();
  let lCALen = cardsArray.length;
  
  for (let i = 0; i < lCALen; ++i) { //make it efficient for checking length
    // Creating a text object for display purposes only
    let newText = $('<p>').append(cardsArray[i].value);
    
    // Creating a new card
    let newCard = $('<div>').attr({
      'data-value': cardsArray[i].value,
      'style': 'background-color:' + cardsArray[i].color,
      'index': i,
      'class': 'card'
      }).append(newText);
      
    squaresParent.append(newCard);
  }
}

drawSquares();
assignEvents();

let firstCard = null;
let secondCard = null;

function compareAndMove(fC, sC) {
  //console.log("Switching...");
  
  let firstCardIndex = fC.attr("index");
  let secondCardIndex = sC.attr("index");
  
  let beforeSecondCardIndex = 0;
  if (secondCardIndex > 0)
    beforeSecondCardIndex = secondCardIndex - 1;
  
  let firstCard = cardsArray[firstCardIndex];
  let secondCard = cardsArray[secondCardIndex];
  let beforeSecond = cardsArray[beforeSecondCardIndex];

  if (firstCard.value - 1 === beforeSecond.value) {
    let temp = firstCard;
    cardsArray[firstCardIndex] = secondCard;
    cardsArray[secondCardIndex] = temp;
    
    drawSquares();
    assignEvents();
  } else {
    fC.removeClass("selected");
    sC.removeClass("selected");
  }
  
  //console.log("Exiting...");
}

function assignEvents() {
  $(".card").click(function() {
    //console.log("Card clicked");

    if (!firstCard) {
      firstCard = $(this);
      firstCard.addClass("selected");
      return;
    }

    if (!secondCard) {
      secondCard = $(this);
      secondCard.addClass("selected");
    }

    compareAndMove(firstCard, secondCard);
    firstCard = null;
    secondCard = null;
  });
}
.card {
  width: 50px;
  height: 50px;
  
  border-radius: 10px;
  border: 1px solid black;
  display: inline-block;
  text-align: center;
  margin: 5px;
}

.selected {
 border: 3px solid black;
}

body {
  background-color: #ABCDEF;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
    <body>
      <div id="squaresParent"></div>
    </body>
</html>
用户回答回答于

试试下面的代码:

var currentCard = $(".cards").first();
var currentCardInd = $(currentCard).attr("index");

$(".cards").on("click", function(event){
    if(currentCard && parseInt(currentCardInd) < parseInt($(this).attr("index"))){
      currentCard.attr("index", $(this).attr("index"));
      $(this).attr("index", currentCardInd.toString());
      $(this).swapWith(currentCard);
      currentCard = $(".cards[index='"+$(this).attr("index")+"']").next();
      currentCardInd = $(currentCard).attr("index");
    }
});


jQuery.fn.swapWith = function(_with) {
    return this.each(function() {
        var copyWith = $(_with).clone(true);
        var copyOrig = $(this).clone(true);
        $(_with).replaceWith(copyOrig);
        $(this).replaceWith(copyWith);
    });
};
.cards{
  padding:10px;
  background-color:lightblue;
  display:inline-block;
  cursor:pointer;
  border-radius:5px;
}

#card-7S{
  background-color:lightgreen;
}
#card-9D{
  background-color:lightyellow;
}
#card-8H{
  background-color:lightgray;
}
#card-3D{
  background-color:lightpink;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
  <div id="card-2d" class="cards" index="2">2D</div>
  <div id="card-7S" class="cards" index="4">7S</div>
  <div id="card-9D" class="cards" index="7">9D</div>
  <div id="card-8H" class="cards" index="10">8H</div>
  <div id="card-3D" class="cards" index="15">3D</div>
</div>

扫码关注云+社区

领取腾讯云代金券