我编写了一个函数来检查输入值以确定要显示的 Font Awesome 图标:
function xOrCheck(condition, childNumber) {
if (condition) {
$("ul.reqs li:nth-child(childNumber) i.fa").removeClass("fa-check-circle");
$("ul.reqs li:nth-child(childNumber) i.fa").addClass("fa-times-circle");
} else {
$("ul.reqs li:nth-child(childNumber) i.fa").removeClass("fa-times-circle");
$("ul.reqs li:nth-child(childNumber) i.fa").addClass("fa-check-circle");
}
}
$('input#demo').on('focus keyup',function(){
var value = $(this).val();
var firstChar = value.substring(0,1);
xOrCheck(firstChar > 5 , 1);
}
这是 HTML:
<input id="demo" value="4132" />
<ul class="reqs">
<li><i class="fa fa-check-circle"></i> Test Item</li>
<li><i class="fa fa-check-circle"></i> Test Item</li>
</ul>
我觉得存在范围问题,但我无法弄清楚。
最佳答案
首先,在您的 html 中,为值添加引号:
<input id="demo" value="4132" />
<ul class="reqs">
<li><i class="fa fa-check-circle"></i> Test Item</li>
<li><i class="fa fa-check-circle"></i> Test Item</li>
</ul>
并且在您的js中,您没有正确使用函数参数:
function xOrCheck(condition, childNumber) {
if (condition) {
$("ul.reqs li:nth-child(" + childNumber + ") i.fa").removeClass("fa-check-circle");
$("ul.reqs li:nth-child(" + childNumber + ") i.fa").addClass("fa-times-circle");
} else {
$("ul.reqs li:nth-child(" + childNumber + ") i.fa").removeClass("fa-times-circle");
$("ul.reqs li:nth-child(" + childNumber + ") i.fa").addClass("fa-check-circle");
}
}
$('input#demo').on('focus keyup',function(){
var value = $(this).val();
var firstChar = value.substring(0,1);
xOrCheck(firstChar > 5 , 1);
}
你可以简化一切:
function xOrCheck(condition, childNumber) {
var $icon = $("ul.reqs li:nth-child(" + childNumber + ") i.fa");
if (condition) {
$icon.removeClass("fa-check-circle").addClass("fa-times-circle");
} else {
$icon.removeClass("fa-times-circle").addClass("fa-check-circle");
}
}
关于javascript - 根据输入值切换图标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31036115/