嘿,伙计们,我试图在html表中添加一个新的单元格,同时检查表中的副本。我在表上循环以检查副本,但是我希望这个警报只显示是否有重复的?现在,警报正在循环使用每个函数吗?这可能是一个简单的任务,但我无法处理。有人能帮我吗?
$("#btnCheck").on("click", function() {
let company_name = $("#test1").val();
$('#companyTable tr').each(function() {
$(this).find('td').each(function() {
if ($(this).text() === company_name) {
alert("duplicate found");
return false;
} else {
alert("duplicate NOT found");
return false;
}
});
});
});<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="companyTable">
<thead>
<tr>
<td>Company Name</td>
</tr>
</thead>
<tbody>
<tr>
<td>toyota</td>
</tr>
<tr>
<td>bmw</td>
</tr>
<tr>
<td>suzuki</td>
</tr>
</tbody>
</table>
<input type="text" id="test1" />
<input type="button" id="btnCheck" value="ADD" />
发布于 2021-07-02 10:00:12
我在JQuery中并不常见,但在普通的JavaScript中,这应该是可行的:
document.querySelector("#btnCheck").onclick = () => {
const companyName = document.querySelector("#test1").value;
let found = false;
document.querySelectorAll("#companyTable td").forEach(cell => {
if(cell.innerText == companyName){
found = true
}
})
alert("duplicate "+(found ? "" : "NOT ")+" found");
}您不需要查询行,那么cells.
found),并且在循环结束时只使用您的结果.注意:在这种情况下使用forEach似乎不是最有效的方法。您应该选择一个临时的for循环,以便在找到匹配时立即对其进行break:
const cells = document.querySelectorAll("#companyTable td");
found = false;
for(let i = 0; i < cells.length; i++){
if(cells[i].innerText == companyName) {
found = true;
break; // Stop the loop
}
}发布于 2021-07-02 10:06:00
从外部循环中提前断开,只有在循环后找不到时才发出警报:
$("#btnCheck").on("click", function () {
let company_name = $("#test1").val();
let found = false;
$('#companyTable tr').each(function () {
$(this).find('td').each(function() {
if ($(this).text() === company_name) {
alert("duplicate found");
found = true;
return false;
}
});
if (found) {
// no need to search through other rows either
return false;
}
});
if (!found) {
alert("duplicate NOT found");
}
});发布于 2021-07-02 10:14:42
在JQuery中,我会使用类似于
$("#companyTable tr td:contains('"+textToSearch+"')")这将返回表id="companyTable“中TR行中的所有TD对象,其中包含"textToSearch”。
https://stackoverflow.com/questions/68222997
复制相似问题