将数组值分配给表格单元格

时间:2017-07-27 23:09:53

标签: javascript arrays html-table

我正在尝试使用Javascript创建一个简单的记忆游戏,并且我创建了一系列字母以匹配游戏,但是,我很难弄清楚如何实际分配单个游戏写作表格的每个单元格的信件。

<html>
<head>
    <style>
    td {
        background-color: red;
        width:100px;
        height:100px;
        border:1px solid black
    }
    </style>
    <table>
        <tr>
            <td id = "tile" onClick = "revealLetter()"></td>
            <td id = "tile" onClick = "revealLetter()"></td>
            <td id = "tile" onClick = "revealLetter()"></td>
            <td id = "tile" onClick = "revealLetter()"></td>
        </tr>
        <tr>
            <td id = "tile" onClick = "revealLetter()"></td>
            <td id = "tile" onClick = "revealLetter()"></td>
            <td id = "tile" onClick = "revealLetter()"></td>
            <td id = "tile" onClick = "revealLetter()"></td>
        </tr>
        <tr>
            <td id = "tile" onClick = "revealLetter()"></td>
            <td id = "tile" onClick = "revealLetter()"></td>
            <td id = "tile" onClick = "revealLetter()"></td>
            <td id = "tile" onClick = "revealLetter()"></td>
        </tr>
        <tr>
            <td id = "tile" onClick = "revealLetter()"></td>
            <td id = "tile" onClick = "revealLetter()"></td>
            <td id = "tile" onClick = "revealLetter()"></td>
            <td id = "tile" onClick = "revealLetter()"></td>
        </tr>
    </table>
<script>
var letters = ['A','A','B','B','C','C','D','D','E','E','F','F','G','G','H','H'];
var square_values = [];
var square_ids = [];
var i = letters.length, j, temp;
while(--i > 0) {
    j = Math.floor(Math.random() * (i+1));
    temp = letters[j];
    letters[j] = letters[i];
    letters[i] = temp;
}

</script>
</head>
<body>

</body>
</html>

2 个答案:

答案 0 :(得分:1)

我建议采用略有不同的方法。我没有构建表格然后输入字母,而是编写了一个基于随机数组构建网格的函数。我从this question借用了一个函数来随机化数组。然后我添加了事件监听器来“翻转”卡片,将他们的值更改为data-letter属性。

我没有编写其余的游戏逻辑 - 我不想踩你的脚趾!显然你想要这样做,如果你翻过两个不匹配,他们会回去再试一次,但是如果他们这样做了,他们就会继续展示 - 我相信你可以运用逻辑和修改我添加事件监听器的函数。

buildGrid();

//global
var a, b = '';


function buildGrid() {
  var letters = ['A', 'A', 'B', 'B', 'C', 'C', 'D', 'D', 'E', 'E', 'F', 'F', 'G', 'G', 'H', 'H'];
  var randomised = shuffle(letters);
  var num_letters = randomised.length;
  var str_tbl = '';

  while (num_letters >= 4) {
    str_tbl += '<tr>';
    for (var i = 0; i < 4; i++) {
      str_tbl += '<td data-letter="' + randomised[i] + '">?</td>';
    }
    str_tbl += '</tr>';
    ranomdised = randomised.splice(0, 4);
    num_letters -= 4;
  }

  var tbl = document.createElement('table');
  tbl.innerHTML = str_tbl;
  document.getElementsByClassName('grid')[0].appendChild(tbl);
  addEventListeners();
}

function addEventListeners(){

	var tds = document.getElementsByTagName( 'td' );
  
  for( var i = 0; i < tds.length; i++  ){
  	tds[i].addEventListener( 'click', function(){
    	this.innerHTML = this.getAttribute( 'data-letter');
      this.className += ' chosen';
    });
  }

}


// borrowed from https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array
function shuffle(array) {
  var currentIndex = array.length,
    temporaryValue, randomIndex;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}
td {
  background-color: #cccccc;
  text-align: centre;
  padding: 20px;
  height: 100px;
  width: 100px;
  color: #333333;
  font-family: helvetica, arial, sans-serif;
  font-size: 30px;
  font-weight: bold;
  cursor: pointer;
}

td:hover {
  background-color: #dddddd;
}

td.chosen {
  background-color: lightblue;
}
<div class="grid"></div>

答案 1 :(得分:0)

您需要将参数从单击表传递到单击处理程序代码,以指示单击了哪个表元素及其在字母数组中的位置。

有很多方法可以做到这一点,包括使用Event对象,但这是一个简单的想法。

  1. 删除所有id属性。无论如何,它们不应该重复。
  2. 更改每个&#34; onclick =&#34;代码片段,用于发送已单击的元素和要使用的下标。所以&#34; onclick&#34;规格看起来像

    onclick="revealLetter( this, 0)"
    // through to
    onclick="revealLetter( this, 15)"
    
  3. 然后将代码revealLetter作为参数:

    function revealLetter( tdElement, subscript) {
    // where tdElement is the table data element clicked, and
    // subscript is a subscript to look its letter up in an array
    // ... insert code here
    

    如前所述,有很多方法可以做到这一点,但您可以使用这种相当简单的方法,同时获得更多经验。

    别忘了查看内心HTML&#34;和&#34; textContent&#34;如果你还没有听说过它们,请说MDNW3Schools。 (它们是HTML元素的属性)