在某些时候,我决定需要一个方便的jQuery选择器来从x到y选择td:nth-child
行。我没有编写[:]
表达式选择器,而是采用了一种插件方法 - 假设它应该像.find()
或.prevAll()
那样正常工作。
$.fn.nthTdInRows = function (n, sRow, eRow) {
return this
.filter(function (index, el) {
return el.tagName.toLowerCase() === 'table';
})
.find('tr')
.filter(function (index) {
return index + 1 >= sRow && index + 1 <= eRow;
})
.find('td:nth-child(' + n + ')');
}
虽然此代码有效,但它仅适用于集合中的第一个表。这很可能是因为插件中缺少.each()
,但是当我想要返回值时,我不知道如何使用它。这可以沿着我选择的路径完成吗?
答案 0 :(得分:1)
好的,所以这里是你如何让它为每个表提供一系列jQuery集合。如果这是您正在寻找的,请告诉我:
.nthTdInRows()
调用中链接jQuery函数。
$.fn.nthTdInRows = function(n, sRow, eRow) {
var arr = this.map(function() { // <-- this calls the following code for each table
// passed in, and maps each return value into an array element
var tables = $(this).filter(function(index, el) {
return $(this).is("table");
});
var tableRows = tables.find("tr");
var indexedRows = tableRows.filter(function(index) {
return index + 1 >= sRow && index + 1 <= eRow;
});
var tds = indexedRows.find('td:nth-child(' + n + ')');
return tds;
});
//debugger;
var collection = [];
arr.each(function() {
// flatten arr into simple array of DOM elements, rather than nested jQuery collections
collection = collection.concat($.map(this, function(elem, index) {
return elem;
}));
});
// wrap array of DOM elements with jQuery object so we can chain off of nthTdInRows()
return $(collection);
}
$(function() {
var tables = $("#table1, #table2, #table3");
tables.nthTdInRows(2, 1, 4).addClass("highlight");
});
.highlight {
background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://code.jquery.com/jquery-2.2.4.js"></script>
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<table id="table1">
<tr>
<th>header1</th>
<th>header2</th>
</tr>
<tr>
<td>data1-1</td>
<td>data2-1</td>
</tr>
<tr>
<td>data1-2</td>
<td>data2-2</td>
</tr>
<tr>
<td>data1-3</td>
<td>data2-3</td>
</tr>
<tr>
<td>data1-4</td>
<td>data2-4</td>
</tr>
</table>
<table id="table2">
<tr>
<th>header3</th>
<th>header4</th>
</tr>
<tr>
<td>data3-1</td>
<td>data4-1</td>
</tr>
<tr>
<td>data3-2</td>
<td>data4-2</td>
</tr>
<tr>
<td>data3-3</td>
<td>data4-3</td>
</tr>
<tr>
<td>data3-4</td>
<td>data4-4</td>
</tr>
</table>
<table id="table3">
<tr>
<th>header5</th>
<th>header6</th>
</tr>
<tr>
<td>data5-1</td>
<td>data6-1</td>
</tr>
<tr>
<td>data5-2</td>
<td>data6-2</td>
</tr>
<tr>
<td>data5-3</td>
<td>data6-3</td>
</tr>
<tr>
<td>data5-4</td>
<td>data6-4</td>
</tr>
</table>
</body>
</html>