简体   繁体   English

如何获取表tds的类名并将其写入到使用jQuery的数组?

[英]How to get class names of table tds and write it to an array using jQuery?

I have HTML table with three rows and three cells for each row. 我有HTML表,其中包含三行,每行三个单元格。 Each cell has class name. 每个单元格都有类名称。 I want to get the class name of each cell and write it to array. 我想获取每个单元格的类名称并将其写入数组。

HTML table: HTML表格:

<table>
    <tr>
        <td class="O-marker"></td>
        <td class="O-marker"></td>
        <td class="X-marker"></td>
    </tr>
    <tr>
        <td class="X-marker"></td>
        <td class="O-marker"></td>
        <td class="X-marker"></td>
    </tr>
    <tr>
        <td class="X-marker"></td>
        <td class="O-marker"></td>
        <td class="O-marker"></td>
    </tr>
</table>

When the getBoard function is called, then get all the class names of cells and write it to board array. 调用getBoard函数时,然后获取单元的所有类名称并将其写入board数组。

function getBoard() {
   var board = [];
   return board;
}

I want to use jQuery and .each() method to get the class name and push the first character into the array board . 我想使用jQuery和.each()方法获取类名并将第一个字符推入阵列board Example. 例。 By the first character I mean (X or O). 我用第一个字符表示(X或O)。

Using vanilla JS: 使用香草JS:

function getBoard() {
  var board = [];
  var tds = document.getElementsByTagName('td');
  for (var i = 0; i < tds.length; i += 1) {
    board.push(tds[i].className[0]);
  }
  return board;
}

Or in jQuery: 或在jQuery中:

function getBoard() {
  var board = [];
  $('td').each(function(){
    board.push(this.className[0]);
  });
  return board;
}

Using jQuery: 使用jQuery:

function getBoard() {
   var board = [];

   $('.table td').each(function (index) {
       board.push($(this).attr('class')[0]);
   });

   return board;
}

console.log(getBoard());

You can treat the string as an array (sort of?) and get the first character with [0] . 您可以将字符串视为数组(排序?),并使用[0]获取第一个字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM