javascript jQuery选择器抓取同一列中的单元格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14061123/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery selector to grab cells in the same column
提问by brentonstrine
Given a multirow, multicolumn table, how can I select all cells in the same columnas any arbitrary cell (e.g. a cell that is clicked on).
给定一个多行、多列的表,如何选择与任意单元格(例如,单击的单元格)在同一列中的所有单元格。
Something like:
就像是:
$("td").click(function(){
var columnNo = $(this).columnNo?
$(this).closest("table").find("tr td:eq("+columnNo+")").css("color", "red");
});
I need to do this without naming the columns individually. E.g. it should work on simple generic table
markup without extra classes or IDs..
我需要在不单独命名列的情况下执行此操作。例如,它应该可以在table
没有额外类或 ID 的情况下处理简单的通用标记。
回答by nbrooks
Your attempt is right, all you need to do is use .index
to find the column number—the index of the <td>
within the row. You also need to use the nth-child-selectorto match the column indices of the other <td>
elements.
你的尝试是对的,你需要做的就是.index
找到列号——<td>
行内的索引。您还需要使用nth-child-selector来匹配其他<td>
元素的列索引。
$("td").click(function(){
var columnNo = $(this).index();
$(this).closest("table")
.find("tr td:nth-child(" + (columnNo+1) + ")")
.css("color", "red");
});
回答by Austin
This can be done using the jQuery eq
method.
这可以使用 jQueryeq
方法来完成。
var $tds = $("td"); // get all tds beforehand, so jquery doesn't
// need to hit the DOM every click
$("td").on("click", function () {
var position = $(this).index(),
$tdsInColumn = $tds.filter(":nth-child(" + index + ")");
// manipulate $tdsInColumn in any way
$tdsInColumn.addClass("selected");
});
Not sure if this is the most efficient way of doing so, but it is the solution I came up with when faced with the same problem a while back.
不确定这是否是最有效的方法,但这是我在不久前遇到同样问题时想到的解决方案。