如何使用jQuery确定某个HTML表头是否存在?

leo*_*ora 0 javascript jquery html-table

假设我有下表:

<table id="mytable">
<thead>
  <tr>
    <th>Col 1</th>
    <th>Col 2</th>
    <th>Col 4</th>
  </tr>
</thead>
<tbody>
    <td>1</td>
    <td>2</td>
    <td>3</td>
</tbody>
Run Code Online (Sandbox Code Playgroud)

并且我想根据是否有该文本的“ th”来查看是否有特定的列?是否可以使用下面的“ HasColumn”方法?

  var hasCol = HasColumn("#mytable", "Col 1");
  //hasCol = true;

  var hasCol = HasColumn("#mytable", "Col 50");
  //hasCol = false;
Run Code Online (Sandbox Code Playgroud)

und*_*ned 5

您可以使用:contains选择器,但不使用完全匹配标准,即,如果您传递Col 1给选择器,并且其中一个元素具有Col 12文本内容,则它将选择该元素,因为它包含指定的文本。我会使用该filter方法:

var hasColumn = $('#mytable thead th').filter(function() {
   return this.textContent === 'Col 1';
}).length > 0;
Run Code Online (Sandbox Code Playgroud)

这是一种普通的JavaScript替代方法:

function hasColumn(tblSel, content) {
    var ths = document.querySelectorAll(tblSel + ' th');
    return Array.prototype.some.call(ths, function(el) {
         return el.textContent === content;
    });
};

var hasCol = hasColumn('#mytable', 'Col 1');
Run Code Online (Sandbox Code Playgroud)