我在中继器中有一张 table 。数据被输入到表中,并根据加载的数据类型为每行分配一个类。例如:
<table id="detail-table">
<tr class="typeA">
<td>Value</td>
</tr>
<tr class="typeB">
<td>Value</td>
</tr>
<tr class="typeC">
<td>Value</td>
</tr>
<tr class="typeB">
<td>Value</td>
</tr>
<tr class="typeA">
<td>Value</td>
</tr>
</table>
该表格是折叠表格。 typeA 是 header ,typeB 是 typeA 的子项,typeC 是 typeB 的子项。在表示例中,typeA 有两个直接子级,第一个子级也有一个子级。
当用户单击 typeA 时,会出现两个 typeB 行,并且当 typeB 有子项时,它也会展开以显示 typeC 行。我有一个事件处理程序,可以在单击时执行此操作。
我需要对具有特定值的项目应用完整的详细信息扩展(typeA 到 typeC)。当 typeA 中的单元格值等于从查询字符串接收到的值时,我需要在父级及其所有子级上触发展开事件。我已经有一些代码可以做到这一点。然而,我觉得这有点黑客行为。我想知道是否有人有一些建议?这是我到目前为止所拥有的。
$(function() {
var tableRows = $('#detail-table').find("tr:gt(0)");
$(tableRows).each(function(i, val) {
//ExpandValue is a value in my C# page.
if ($.trim(val.cells[0].innerText) == '<%= ExpandValue %>'){
expandRows(i);
}
}
function expandRows(startIndex) {
// Expand the first row, the typeA class
// row that matches the value
$(tableRows[startIndex]).trigger('expand');
startIndex += 1;
while($(tableRows[startIndex]).attr("class") != "typeA"){
$(tableRows[startIndex]).trigger('expand');
startIndex++;
}
}
});
这会找到表中的所有行。然后循环遍历表行数组。该条件检查每行中第一个单元格的内部文本。如果单元格的innerText与ExpandValue匹配,则已找到目标行。将该行的索引发送到 ExpandRows 函数。在expandRows函数中,展开startIndex处的行,这是与ExpandValue匹配的typeA类行。然后将 startIndex 加一以指向下一行。 while 循环检查每行的类。在每一行上触发展开事件,直到命中下一个 typeA 行。这可以正常工作并扩展每一行。但同样,我是 jquery 的新手,我觉得可能有某种方法可以更好地完成此任务。有什么想法吗?
最佳答案
您可以加快代码顶部的选择器和循环速度:
//instead of using a pseudo-selector, we can use the `slice()` function to get all but the first element returned
var $tableRows = $('#detail-table').find("tr").slice(1);
//this `for` loop will perform a lot faster than the `.each()` loop
for (var i = 0, len = $tableRows.length; i < len; i++) {
if ($.trim($tableRows.eq(i).find('td').eq(0).text()) == '<%= ExpandValue %>') {
expandRows(i);
}
}
这里演示了正确格式化的 for
循环比使用 jQuery 的 .each()
快得多:http://jsperf.com/jquery-each-vs-for-loops/2
这里有一些文档供您引用:
.slice()
:http://api.jquery.com/slice.eq()
:http://api.jquery.com/eq.text()
:http://api.jquery.com/text
此外,您继续将 tableRows
变量包装在 jQuery 中,这是没有必要的,因为它从一开始就已经是一个 jQuery 对象。
$(function() {
var $tableRows = $('#detail-table').find("tr").slice(1);
for (var i = 0, len = $tableRows.length; i < len; i++) {
if ($.trim($tableRows.eq(i).find('td').eq(0).text()) == '<%= ExpandValue %>') {
expandRows(i);
}
}
function expandRows(startIndex) {
// Expand the first row, the typeA class
// row that matches the value
$tableRows.eq(startIndex).trigger('expand');
startIndex++;
while($tableRows.eq(startIndex).attr("class") != "typeA"){
$tableRows.eq(startIndex).trigger('expand');
startIndex++;
}
}
});
我不确定这是否已经完成了您想要的操作,但是在您的 expandRows
函数上,您可能应该在执行任何操作之前将 startIndex
加一,因为如果第一个通过 for
循环进行迭代会触发 expandRows()
函数,然后它将传递一个索引为零的索引,该索引将定位顶行(您在开始时将其从选择器中排除) .
关于javascript - 将 jquery 事件应用于表中的特定范围或行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9164209/