如何获取表格单元格的列索引

时间:2017-03-02 14:21:27

标签: jquery html

如何获取jQuery中表中任何HTML divider元素的列索引?这是我的HTML:

table {
	border:1px solid navy;
	width: 70%;
	text-align: center;
}
table th {
	text-align: center;
	width:100px;
	height:20px;
}
table td {
	width: 100px;
	height: 100px;
	vertical-align: top;
	text-align: right;
	border: 1px solid #c6c6ec;
}
<table>
  <tbody>
    <tr>
      <th>Header</th>
    </tr>
    <tr>
      <th>Header1</th><th>Header2</th><th>Header3</th>
    </tr>
    <tr>
      <td></td>
      <td></td>
      <td></td>
    </tr>
    <tr>
      <td></td>
      <td>Want this column index e.g.</td>
      <td></td>
    </tr>
    </tbody>
</table>

我设法使用以下jQuery获取行索引:

var text_var = "Want this column index e.g."
var elem = $('td').filter(function() { 
        var Text = $(this).contents()[0].textContent.trim();
        return parseInt(Text, 10) == text_var;
    });
var row_index_first = elem.parent().index();

我想用类似的东西获取专栏......?

由于

1 个答案:

答案 0 :(得分:2)

逻辑非常相似,您只需直接检查text()而不将其转换为整数,然后在index()上调用elem。试试这个:

&#13;
&#13;
var text_var = "Want this column index e.g."
var elem = $('td').filter(function() {
  return $(this).text().trim() == text_var;
});
var row_index_first = elem.index();

console.log(row_index_first);
&#13;
table {
  border: 1px solid navy;
  width: 70%;
  text-align: center;
}

table th {
  text-align: center;
  width: 100px;
  height: 20px;
}

table td {
  width: 100px;
  height: 100px;
  vertical-align: top;
  text-align: right;
  border: 1px solid #c6c6ec;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tbody>
    <tr>
      <th>Header</th>
    </tr>
    <tr>
      <th>Header1</th>
      <th>Header2</th>
      <th>Header3</th>
    </tr>
    <tr>
      <td></td>
      <td></td>
      <td></td>
    </tr>
    <tr>
      <td></td>
      <td>Want this column index e.g.</td>
      <td></td>
    </tr>
  </tbody>
</table>
&#13;
&#13;
&#13;