簡體   English   中英

在JavaScript中索引HTML div類

[英]Indexing HTML div classes in JavaScript

我正在嘗試使用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的值是否比第二張多1的卡的值大一。

這是我一直在嘗試使用的代碼:

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

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

卡是一個數組,其中包含我所有的div類。 我收到的一個錯誤告訴我indexOf在這里不是可用的函數。 我認為這可能是因為div類實際上不是數組的一部分,並且我需要一種不同的方法來查找某物的“值”而不是“索引”。

例如,如果一行紙牌變為2D,7S,9D,8H,3D,則用戶可以為firstCard單擊3D,為secondCard單擊7S。 該函數將驗證3D的值是否比2D大1,並將交換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> 

您也可以在這里檢查。.https ://jsfiddle.net/nimittshah/7z3y8mb5/

代碼的問題是querySelectorAll()返回一個NodeList ,其行為類似於數組,但實際上不是數組。

與getElementsByClassName()發生相同的問題,這是一個返回HTMLCollection的行為,該HTMLCollection表現為數組,但不包含所有原型功能,因為它實際上不是數組。

因此,您有多種選擇來獲取索引,在獲取索引之后,您可以獲取它之前的元素。

使用調用或應用來欺騙Array方法

`Array.prototype.indexOf.call(cards, second)`

手動迭代

`let selectedIndex = 0;
for(let i =0; i < cards.length; i++){
  if(cards[i] === second){
    selectedIndex = i;
  }
};
console.log(selectedIndex)`

使用卡片NodeList創建陣列

const cards = document.querySelectorAll('.card'); const cardsArray = Array.from(cards) if(firstCard.dataset.value === cardsArray[cardsArray.indexOf(secondCard)-1].dataset.value)

使用任何庫來選擇返回數組的元素,如jQuery

Array.from是獲取元素數組的規范方法

<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>

<script>
  const [first, second] = Array.from(document.querySelectorAll('.card'))
  if (first.dataset.value === second.dataset.value) {
    /* do your thing... */
  }
</script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM