功能:
有一张水果(苹果,香蕉)和它们的颜色(红色,黄色)的桌子。
需求:
找到水果,输出其颜色。如果不存在水果,则“未找到水果”。
问题:
第一个结果是正确的(表中没有“ pear”,但随后的结果是错误的(“ pear is red?”)。
我尝试使用color
或var color
而不是全局变量在本地声明let 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>
因为color
是全局变量,所以在运行findFruitColor("#myTable", "apple");
之后它仍然是“红色”。要解决该问题,只需将其声明为findFruitColor
的局部变量即可。像这样的东西:
function findFruitColor(table, fruit) {
let colKey = $(table).find("th:contains('Fruit')").index();
let colVal = $(table).find("th:contains('Color')").index();
// Declare color here
let color;
$(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>