【发布时间】:2018-01-20 08:33:00
【问题描述】:
我正在尝试创建一个脚本来根据输入字段中的第一个字符更改信用卡图像。
我能够毫无问题地捕获第一个字符,但是当我设置条件时,无论输入什么字符,第一个 if 语句都会显示为 true。
我创建了一个jsFiddle here。添加了一些控制台日志,显示第一个字符被正确捕获,但第一个条件总是触发为真。
HTML
<div class="container">
<div class="col-sm-6 col-sm-offset-3 col-xs-offset-0">
<div class="form-group">
<label>Credit Card Number</label>
<input class="credit-card" type="text"/><i class="fa"></i>
</div>
</div>
</div>
jQuery
$(document).ready(function(){
$('.form-group').on('click',function(){
$(this).find('label').addClass('moveUp');
});
$('.credit-card').keyup(function(){
var firstChar = $(this).val().charAt(0);
console.log(firstChar)
if ($(firstChar === 4)) {
console.log('yup, you got a four');
$(this).closest('.form-group').find('.fa').addClass('fa-cc-visa active');
} else if ($(firstChar === 5)) {
console.log('yup, you got a five');
$(this).closest('.form-group').find('.fa').addClass('fa-cc-mastercard active');
} else {
$(this).closest('.form-group').find('.fa').removeAttr('class').addClass('fa');
}
});
});
【问题讨论】:
-
您还想与字符串进行比较...
firstChar === "5"例如 -
好电话 - 我也会加入。
标签: javascript jquery html