jquery - 如何避免 .each 方法中的重复值
问题描述
附加表代码
var tr = '<tr id="trdata" ><td class="code" >'+item_name+'</td><td class="itemname" >'+item_name2+'</td> <td class="qty" >'+qty+'</td><td class="rate" >'+rate+'</td> <td class ="grand">'+total+'</td> <td><button type = "button" class="btn btn-danger btn-xs" >Remove</button></td></tr>';
$('tbody').append(tr);
$("#form2")[0].reset();
}
价值获取代码
$('#save').click(function(){
var code = [];
var itemname = [];
var qty = [];
var rate = [];
var grand = [];
$('.code').each(function(){code.push($(this).text());});
$('.itemname').each(function(){itemname.push($(this).text());});
$('.qty').each(function(){qty.push($(this).text());});
$('.rate').each(function(){rate.push($(this).text());});
$('.grand').each(function(){grand.push($(this).text());});
});
在我的控制台中显示重复值
"console.log(code);"
[]
0: "3"
1: "3"
length: 2
如何避免这种重复,它在使用插入查询时也插入到我的数据库中
解决方案
你可以测试.includes()
$('.code').each(function(){
if (!code.includes($(this).text()) {
code.push($(this).text());
}
});
但是,如果您需要保持所有数组同步,您应该在行上使用一个循环,而不是为每个字段单独循环。
$("tr").each(function() {
var curCode = $(this).find(".code").text();
if (!code.includes(curCode)) {
code.push(curCode);
itemname.push($(this).find(".itemname").text());
qty.push($(this).find(".qty").text());
rate.push($(this).find(".rate").text());
grand.push($(this).find(".grand").text());
}
});
推荐阅读
- json - 将 Json 字段从 SQL 返回到 ASP.NET Core API
- html - 为什么即使我指定了 DL 标签的宽度,它也会使用所有空间?
- c# - 如何将字符串转换为类型?
- json - Swift:将字典转换为 JSON 以用于多部分/表单数据
- c# - 我可以使用 Accord.Net 进行并发 cobyla 优化吗?
- python - `poetry lock` 和 `poetry update --lock` 有什么区别?
- list - 如果找不到其中一个包,如何防止 apt/apt-get 取消下载多个包
- javascript - Vega-Lite 工具提示未以 UTC 显示时间
- java - 单击 RecyclerView 后,当我想在新活动中显示详细信息时出现错误。使用 Firebase
- c++ - 与 CMake 链接后的“未定义引用”