为什么我在使用 jQuery 和 JavaScript 时得到不同的结果
Why I get different results when using jQuery and JavaScript
这是我的html代码
<table id="example" class="display" style="width:100%">
<tbody>
<tr class="data">
<td>1</td>
</tr>
<tr class="data">
<td>2</td>
</tr>
<tr class="data">
<td>3</td>
</tr>
<tr class="data">
<td>4</td>
</tr>
<tr class="data">
<td>5</td>
</tr>
<tr class="data">
<td>6</td>
</tr>
<tr class="data">
<td>7</td>
</tr>
</tbody>
</table>
并且我使用 jQuery 数据表和 jQuery
的脚本
$('#example').DataTable({
"lengthMenu": [[5, 25, 50, -1], [5, 25, 50, "All"]],
"columnDefs": [
{ type: "num", targets: 0 },
]
});
而且我不明白为什么我在下面使用这段代码会显示 2 个不同的结果
list= document.getElementsByClassName("data");
console.log(list.length); // 7
$('button').on('click', function() {
console.log(list.length); //5
});
感谢您的帮助。
您的第一个 console.log(list.length);
会在 $('#example').DataTable
之前执行,它将 return 7
因为有 7
行 class data
.
那是因为一旦你申请了$('#example').DataTable
它只会渲染(显示)5 rows
,所以当你使用list.length
它会return 5
.
仅供参考 - 当您编写 list = document.getElementsByClassName("data");
时,Document.getElementsByClassName()
不会 cache
生成 list
对象。这意味着当您在 click
中使用 list.length
时,它将执行 document.getElementsByClassName("data").length
。每次使用 list
时,它都会一次又一次地扫描整个文档。
参考 - Document.getElementsByClassName()
Warning: This is a live HTMLCollection. Changes in the DOM will reflect in the array as the changes occur. If an element selected by this array no longer qualifies for the selector, it will automatically be removed. Be aware of this for iteration purposes.
这是我的html代码
<table id="example" class="display" style="width:100%">
<tbody>
<tr class="data">
<td>1</td>
</tr>
<tr class="data">
<td>2</td>
</tr>
<tr class="data">
<td>3</td>
</tr>
<tr class="data">
<td>4</td>
</tr>
<tr class="data">
<td>5</td>
</tr>
<tr class="data">
<td>6</td>
</tr>
<tr class="data">
<td>7</td>
</tr>
</tbody>
</table>
并且我使用 jQuery 数据表和 jQuery
的脚本$('#example').DataTable({
"lengthMenu": [[5, 25, 50, -1], [5, 25, 50, "All"]],
"columnDefs": [
{ type: "num", targets: 0 },
]
});
而且我不明白为什么我在下面使用这段代码会显示 2 个不同的结果
list= document.getElementsByClassName("data");
console.log(list.length); // 7
$('button').on('click', function() {
console.log(list.length); //5
});
感谢您的帮助。
您的第一个 console.log(list.length);
会在 $('#example').DataTable
之前执行,它将 return 7
因为有 7
行 class data
.
那是因为一旦你申请了$('#example').DataTable
它只会渲染(显示)5 rows
,所以当你使用list.length
它会return 5
.
仅供参考 - 当您编写 list = document.getElementsByClassName("data");
时,Document.getElementsByClassName()
不会 cache
生成 list
对象。这意味着当您在 click
中使用 list.length
时,它将执行 document.getElementsByClassName("data").length
。每次使用 list
时,它都会一次又一次地扫描整个文档。
参考 - Document.getElementsByClassName()
Warning: This is a live HTMLCollection. Changes in the DOM will reflect in the array as the changes occur. If an element selected by this array no longer qualifies for the selector, it will automatically be removed. Be aware of this for iteration purposes.