gpt4 book ai didi

javascript - 为什么我可以按 int 而不是 string 过滤?

转载 作者:行者123 更新时间:2023-11-30 16:25:23 26 4
gpt4 key购买 nike

现在我有可以按 int 过滤的代码:

<input name='tablefilter' type='checkbox' value='1' id='tablefilter1' checked/>
<label for='tablefilter1'>1</label>
<input name='tablefilter' type='checkbox' value='2' id='tablefilter2' checked/>
<label for='tablefilter2'>2</label>
<input name='tablefilter' type='checkbox' value='3' id='tablefilter3' checked/>
<label for='tablefilter3'>3</label>
<table>
<thead>
<tr>
<th>Col1</th>
<th>Col2</th>
<th>Col3</th>
</tr>
</thead>
<tbody id='tablebody'>
<tr>
<td>1</td>
<td>One</td>
<td>First</td>
</tr>
<tr>
<td>2</td>
<td>Two</td>
<td>Second</td>
</tr>
<tr>
<td>3</td>
<td>Three</td>
<td>Third</td>
</tr>
</tbody>
</table>

js

/* Demo filtering table using checkboxes. Filters against first td value */

/* Set 'ready' handler' */
document.addEventListener('DOMContentLoaded', initFunc);

/* When document ready, set click handlers for the filter boxes */
function initFunc(event) {
var filters = document.getElementsByName('tablefilter');
for (var i = 0; i < filters.length; i++) {
filters[i].addEventListener('click', buildAndExecFilter);
}
}

/*
This function gets called when clicking on table filter checkboxes.
It builds a list of selected values and then filters the table based on that
*/
function buildAndExecFilter() {
var show = [];
var filters = document.getElementsByName('tablefilter');
for (var i = 0; i < filters.length; i++) {
if (filters[i].checked) {
show.push(filters[i].value);
}
}
execFilter(show); // Filter based on selected values
}

function execFilter(show) {
/* For all rows of table, see if td 0 contains a selected value to filter */
var rows = document.getElementById('tablebody').getElementsByTagName('tr');
for (var i = 0; i < rows.length; i++) {
var display = ""; // Default to display
// If it is not found in the selected filter values, don't show it
if (show.indexOf(rows[i].children[0].textContent) === -1) {
display = "none";
}
// Update the display accordingly
rows[i].style.display = display;
}
}

http://jsfiddle.net/2Lm7pytt/3/

但是该过滤器不能按字符串过滤。例如,如果我想使用“一”而不是 1,它就不会起作用。

有谁知道为什么以及解决方案是什么?

谢谢

最佳答案

execFilter() 方法的这些行,

 if (show.indexOf(rows[i].children[0].textContent) === -1) {
display = "none";
}

仅比较索引 0,它是数值而不是其他列。

除非您将这些值与所有列(rows[i].children 的所有索引)进行比较,否则它不会给您想要的结果。

因此,您可能不想运行 for 循环来遍历 rows[i].children 的所有子项并比较它们的文本。

var foundResult = false;
for ( var counter = 0; counter < rows[i].children.length; counter++ )
{
if (show.indexOf(rows[i].children[0].textContent) != -1)
{
foundResult= true;
break;
}
}
if ( !foundResult )
{
display = 'none';
}

关于javascript - 为什么我可以按 int 而不是 string 过滤?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34197043/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com