javascript - 根据输入值切换图标

标签 javascript jquery

我编写了一个函数来检查输入值以确定要显示的 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/

相关文章:

c# - Ajax AutoCompleteExtender - 为什么此代码不起作用?

javascript - 有没有办法逆转atan的影响?

jquery - 当我们单击 div 内的复选框时,如何防止 div 折叠?

php - 如何正确使用 jquery 的 getJSON?

javascript - 如何根据PHP中所需的字段显示所有验证错误?

php - 当我点击浏览器的后退按钮时,如何在主页上重定向

javascript - props.items.map 不是使用 React 的函数

javascript - 在 Controller 之前执行指令代码

javascript - 在格式化为数组而不是字符串的 html 文档中打印数组

javascript - nuxt.js - $(...).slider 不是函数