您好我正在尝试开发一个javascript函数,每当输入更改时都会进行一些验证(我使用onkeyup事件)除非我们删除输入内部输入的内容是我的实际代码
function myFunction() {
var input, filter, table, tr, td, i;
var cpt = 0;
var nbRow = 0;
input = document.getElementById("filterInput");
filter = input.value.toUpperCase();
table = document.getElementById("test");
thead = table.getElementsByTagName("tbody");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[2];
if (td) {
nbRow = nbRow + 1;
if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
cpt = cpt + 1;
}
}
}
if (nbRow == cpt) {
alert("The list is empty")
}
}
&#13;
<input id="filterInput" onkeyup="myFunction()">
<table id="test">
<thead>
<tr>
<th>Titre1</th>
<th>Titre2</th>
<th>Titre3</th>
</tr>
</thead>
<tbody>
<tr>
<td>contenu1</td>
<td>contenu2</td>
<td>contenu3</td>
</tr>
</tbody>
</table>
&#13;
每次用户删除一个字符时,如何避免重复的alert
节目?
编辑:
我试图避免重复的警告&#39;用户删除一个字符后不丢失验证。
答案 0 :(得分:4)
如果你想用onkeyup忽略删除和退格,你可以将这个检查添加到你的函数的开头:
function myFunction(event) {
// capture what key was pressed
var key = event.keyCode || event.charCode;
if( key === 8 || key === 46 )
return; //if it's del or backspace, exit the function
// continue your function here
}
答案 1 :(得分:1)
您可以在检测按下哪个键的功能中实现验证...
function myFunction(e) {
if(e.keyCode !== 8){ // back key excluded
var input, filter, table, tr, td, i;
var cpt = 0;
var nbRow = 0;
input = document.getElementById("filterInput");
filter = input.value.toUpperCase();
table = document.getElementById("test");
thead = table.getElementsByTagName("tbody");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[2];
if (td) {
nbRow = nbRow + 1;
if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
cpt = cpt + 1;
}
}
}
if (nbRow == cpt) {
alert("The list is empty")
}
}
}
<input id="filterInput" onkeyup="myFunction(event)">
<table id="test">
<thead>
<tr>
<th>Titre1</th>
<th>Titre2</th>
<th>Titre3</th>
</tr>
</thead>
<tbody>
<tr>
<td>contenu1</td>
<td>contenu2</td>
<td>contenu3</td>
</tr>
</tbody>
</table>
当然,您必须为要排除的每个键添加代码