簡體   English   中英

從類的特定元素獲取屬性

[英]Get attribute from a specific element of a class

基本上我必須開發一個 Tic-Tac-Toe 游戲,這是我不能重寫的 HTML 文件,只能重新格式化,但想法應該保持不變。


{% block content %}
    <nav class="navbar fixed-top navbar-light">
        <button id="retry-button" class="btn btn-success">Try again?</button>
        <a href="/" class="btn btn-outline-dark">Reset settings</a>
    </nav>
    <div id="game-board" class="mb-3" data-row-num="{{ row_num }}" data-col-num="{{ col_num }}" data-win-size="{{ win_size }}">
        {% for row in range(row_num) %}
            <div>
                {% for col in range(col_num) %}
                    <div class="game-cell"
                         data-coordinate-x="{{ col }}"
                         data-coordinate-y="{{ row }}"></div>
                {% endfor %}
            </div>
        {% endfor %}
    </div>
{% endblock %}

如您所見,我有一個默認包含 9 個元素的游戲單元類。 當我單擊其中一個游戲單元格時,我想返回數據坐標 x 和數據坐標 y。 我以前嘗試過,但如果我點擊它,它會返回所有塊,而不僅僅是我點擊的塊。 我必須用Js寫它。 如果你能指出我正確的方向,那對我來說就足夠了。 謝謝!

如果我理解正確,您需要訪問游戲單元元素的數據屬性。 為此,您需要通過某個 ID 或類來選擇元素。 我稍微修改了您的代碼,使其在 stackoverflow 的平台內運行。 我添加了一個我稱之為“唯一”的 ID,我還在坐標 x 和 y 數據屬性中設置了一些值。 請查看下面的代碼,看看我是如何獲得這些數據屬性的。 重要的是要注意,這不是訪問它們的唯一方法。

 var gamecell = document.getElementById('unique'); console.log(gamecell.dataset.coordinateX); console.log(gamecell.dataset.coordinateY);
 <nav class="navbar fixed-top navbar-light"> <button id="retry-button" class="btn btn-success">Try again?</button> <a href="/" class="btn btn-outline-dark">Reset settings</a> </nav> <div id="game-board" class="mb-3" data-row-num="{{ row_num }}" data-col-num="{{ col_num }}" data-win-size="{{ win_size }}"> <div> <div class="game-cell" id="unique" data-coordinate-x="172" data-coordinate-y="273"></div> </div> </div>

也可以使用getAttribute方法獲取這些值。

var elem = document.getElementById('unique');

var coordX = elem.getAttribute('data-coordinateX');
var coordY   = elem.getAttribute('data-coordinateY');

請看一下這個頁面,它解釋了數據屬性的一些方面:

https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes

只需通過以下方式訪問您點擊的游戲單元:(它會找到點擊的坐標 X 和坐標 Y)

document.querySelectorAll('.game-cell').forEach((game) => {
   game.addEventListener('click',function(event){
   console.log(game.dataset.coordinateX);
   console.log(game.dataset.coordinateY);
  });
});

你必須通過類名或id(添加一個id)來獲取你的元素,而不是你可以像這樣獲取它的屬性

let gameCell = document.getElementById('game-cell-id');// id for example
gameCell.getAttribute('data-coordinate-x')

暫無
暫無

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

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