我有一个包含许多行的表。我需要使用jquery找到td数据。 有很多方法可以获得这些数据
1. $("table tr td").each(function(){})
2. $("table").find("tr").find("td").each(function(){})
现在我想知道哪种方法更好,为什么?
答案 0 :(得分:5)
使用console.time
和console.timeEnd
进行性能分析会在几微秒内为您提供性能。
console.time('withSelector');
for(var i=0; i<10E4 ;i++)
$("table tr td");
console.timeEnd('withSelector');
同样适用于$("table").find("tr").find("td")
..运行代码段
With selector
优于find
function withSelector() {
$("table tr td");
}
function withFind() {
$("table").find("tr").find("td")
}
function run(fn, times) {
console.time(fn.name);
for(var i=0; i<times ;i++)
fn();
console.timeEnd(fn.name);
}
run(withSelector, 10E4);
run(withFind, 10E4);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
</table>
&#13;