javascript - 使用 Javascript 在表格单元格中查找值
问题描述
我在 HTML 中使用动态表,但我需要验证这些值是否重复。我正在尝试使用单元格内的值而不是文本来执行此操作。这些是价值观以及我到目前为止所拥有的:
var tBody = $("#tablaAplicaciones > TBODY")[0];
//Add Row.
var row = tBody.insertRow(-1);
//Add Name cell.
var cell = $(row.insertCell(-1));
cell.html(nameCountry);
cell.val(idCountry);
//Add Country cell.
cell = $(row.insertCell(-1));
cell.html(nameCompany);
cell.val(idCompany);
if (($('#tablaApp tr > td:contains(' + countryName + ') + td:contains(' + companyName + ')').length) == 1) {
.
.
.
}
解决方案
欢迎来到堆栈溢出。考虑以下代码。
$(function() {
var idCountry = "9";
var nameCountry = "United States";
var idCompany = "9";
var nameCompany = "Genentech";
var tBody = $("#tablaAplicaciones > tbody");
//Create Row
var row = $("<tr>");
//Add Country cell to Row
$("<td>", {
class: "name-country"
})
.data("id", idCountry)
.html(nameCompany)
.appendTo(row);
//Add Company cell to Row
$("<td>", {
class: "name-company"
})
.data("id", idCompany)
.html(nameCompany)
.appendTo(row);
// Assume vales are not in the table
var found = -1;
$("tr", tBody).each(function(i, el) {
// Test each row, if value is found set test to tue
if ($(".name-country", el).text().trim() == nameCountry) {
found = i;
}
if ($(".name-company", el).text().trim() == nameCompany) {
found = i;
}
});
if (found == -1) {
// If test is false, append the row to table
row.appendTo(tBody);
console.log("Row Added", row);
} else {
console.log("Values already in Table, row: " + found);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tablaAplicaciones">
<thead>
<tr>
<th>Country</th>
<th>Company</th>
</tr>
</thead>
<tbody>
<tr>
<td data-id="1" class="name-country">United States</td>
<td data-id="1" class="name-company">Apple Inc.</td>
</tbody>
</table>
使用.each()
,您可以遍历每一行并比较值。变量可以用作标志来指示是否在大海捞针中找到了针。如果没有找到,您可以追加该行。否则,不要添加该行。
希望有帮助。
推荐阅读
- ibm-mq - 如何使用脚本检查远程队列管理器的队列深度?
- python-3.x - 为什么KL散度给了nan?是一些数学错误还是我的输入数据不正确?
- ios - iOS ARKit - Calculate the degree of rotation of device in all three direction
- angular6 - How can we pass dynamic variable from any component.ts to style.less in angular 6?
- reactjs - 以这种方式使用 useEffect 有什么问题吗?
- javascript - 在数据表上显示列的总和(总计)并导出到 excel
- bash - 如何在字符串中的特定模式之后提取特定文本
- highcharts - Highstock - 软最小值和最大值不工作
- android - Android apk Build 输出文件夹中充斥着大量带有时间戳的 apk
- html - NativeScript WebView 未加载 html 文件