我想单击removeFood
div中的一个项目,使其与文本区域newFoodName1
中的项目匹配
$(".removeFood").click(function() {
var removedFood = ($(this).children('.dailyItem').text())
$(this).text('')
var selectedFood = $("#newFoodName1").text();
console.log(removedFood + selectedFood)
if (removedFood == selectedFood) {
console.log('They Match')
} else {
console.log('they dont match')
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='removeFood'>
<p class='dailyItem'>
Eclair
<i class="fas fa-trash-alt"></i>
</p>
</div>
<textarea id='newFoodName1'>Eclair</textarea>
在控制台中,此日志记录Eclair Eclair
,但是if语句表明它们不匹配。我想念什么?
答案 0 :(得分:3)
由于值周围的空格,它们不匹配。如果您使用trim()
删除它,那么if
条件将被匹配:
$(".removeFood").click(function() {
var removedFood = ($(this).children('.dailyItem').text())
$(this).text('')
var selectedFood = $("#newFoodName1").text();
console.log(removedFood + selectedFood)
if (removedFood.trim() == selectedFood.trim()) {
console.log('They Match')
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='removeFood'>
<p class='dailyItem'>
Eclair
<i class="fas fa-trash-alt"></i>
</p>
</div>
<textarea id='newFoodName1'>Eclair</textarea>
答案 1 :(得分:0)
只需使用trim()修剪数据
$(".removeFood").click(function() {
var removedFood = ($(this).children('.dailyItem').text().trim())
$(this).text('')
var selectedFood = $("#newFoodName1").text().trim();
console.log(removedFood + selectedFood)
if (removedFood == selectedFood) {
console.log('They Match')
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='removeFood'>
<p class='dailyItem'>
Eclair
<i class="fas fa-trash-alt"></i>
</p>
</div>
<textarea id='newFoodName1'>Eclair</textarea>