javascript - jQuery - 变量而不是表 id
问题描述
如何使用变量而不是表 id?
例如,我想将 id 替换#myTable
为变量table
。
function findFruitColor(table, fruit) {
let colKey = $("#myTable th:contains('Fruit')").index();
let colVal = $("#myTable th:contains('Color')").index();
$('#myTable tr td:nth-child(' + (colKey + 1) + ')').each(function() {
if ($(this).text() === fruit) {
color = $(this).siblings('td').addBack().eq(colVal).text();
return false;
}
})
// Display the color that was found
if (typeof color !== 'undefined') {
console.log("The color for " + fruit + " is " + color);
}
}
// Call the function
findFruitColor("#myTable", "apple");
th {
font-weight: bold;
width: 11em;
text-align: left;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="myTable">
<tr>
<th>Fruit</th>
<th>Color</th>
</tr>
<tr>
<td>apple</td>
<td>red</td>
</tr>
<tr>
<td>banana</td>
<td>yellow</td>
</tr>
解决方案
推荐阅读
- javascript - 如何在 React js 中实现日历计划器或调度器组件
- java - 为什么 CopyOnWriteArrayList 需要用于写入和读取操作的副本?
- for-loop - 如何在 for 循环中更改结构实例的字段?
- javascript - 如何替换字符串中的标记?
- jenkins - 无法读取詹金斯 config.xml
- reactjs - 为什么我们无法在转换函数中获取状态
- firebase - 推送 Notificatblanion Firebase 失败 - 错误消息为空
- android - 调用 RecyclerView Adapter 和 Fragment 之间的接口导致空指针异常
- python - 有什么方法可以将图像上的文本居中(Python/PIL)?
- python - 你如何使用 $count?