【发布时间】:2020-07-30 10:55:39
【问题描述】:
功能:
有一张水果表(苹果、香蕉)和它们的颜色(红色、黄色)。
要求:
找到一个水果,输出它的颜色。如果不存在果实,则“未找到果实”。
问题:
第一个结果是正确的(“梨”不在表中),但后面的结果是错误的(“梨是红色的?”)。
我尝试使用var color 或let color 在本地声明color 变量而不是全局变量,但没有奏效。我认为我使用的范围或测试条件是错误的。
¯\_(ツ)_/¯
function findFruitColor(table, fruit) {
let colKey = $(table).find("th:contains('Fruit')").index();
let colVal = $(table).find("th:contains('Color')").index();
$(table).find('tr td:nth-child(' + (colKey + 1) + ')').each(function() {
if ($(this).text() === fruit) {
color = $(this).siblings('td').addBack().eq(colVal).text();
return false;
}
})
// if color was found, display it.
if (typeof color !== 'undefined') {
console.log("The color for " + fruit + " is " + color);
} else {
console.log("No fruit matching that name was found.");
}
}
// Call the function
findFruitColor("#myTable", "pear");
findFruitColor("#myTable", "apple");
findFruitColor("#myTable", "pear");
th {
font-weight: bold;
width: 4em;
text-align: left;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/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 jquery