Javascript 不带插件的jquery添加的引导类
为了验证,我正在尝试以引导形式添加一个类。这是我的表格Javascript 不带插件的jquery添加的引导类,javascript,jquery,html,forms,twitter-bootstrap-3,Javascript,Jquery,Html,Forms,Twitter Bootstrap 3,为了验证,我正在尝试以引导形式添加一个类。这是我的表格 <form id= "regForm" method="post" class="form-horizontal"> <div class="form-group has-feedback"> <label for="FirstName" class="col-sm-2 control-label">First Name</label> <div class="col-sm-10">
<form id= "regForm" method="post" class="form-horizontal">
<div class="form-group has-feedback">
<label for="FirstName" class="col-sm-2 control-label">First Name</label>
<div class="col-sm-10">
<input type="text" name="firstName" class="form-control" id="FirstName" placeholder="First Name">
<span class="glyphicon form-control-feedback" aria-hidden="true"></span>
</div>
</div>
</form>
我希望,若名称为null或为空,它应该在现有类中添加引导类glyphicon remove,就像我希望在进一步的表单输入中这样做一样。我不想使用jquery插件,我想学习它。我使用的是Bootstrap3.3.7CDN
谢谢这样就可以了
$(document).ready(function() {
$("#FirstName").focusin(function(){
var is_name = $("input").val();
if(is_name ==='' || is_name === null){
var $this = $(this);
$this.addClass('has-error');
$this.next('span').addClass('glyphicon-remove');
}
});
});
你把条件运算符弄错了。这:
if(is_name ==='' && is_name === null)
需要这样做:
if(is_name ==='' || is_name === null)
因为“is_name”不能同时是空字符串和null,它们是两种不同的东西
接下来,你在哪里有这句话:
$('div').addClass('has-error');
var $this = $(this);
您告诉jQuery将“has error”类添加到页面上的每个div中
相反,您可以使用$(this)获得对刚刚单击的输入的引用,因此现在您可以将类添加到输入本身
您可以使用:
$(this).addClass('has-error');
但由于需要查找“span”标记,因此仍然需要输入的引用,因此最佳做法是使用以下行缓存它:
$('div').addClass('has-error');
var $this = $(this);
现在jQuery为输入保存了一个变量,这对性能更有利
最后,使用jQuery的“next”方法查找span标记,并向其添加“glyphicon remove”类:
$this.next('span').addClass('glyphicon-remove');
希望能有所帮助。谢谢你,克里斯,因为我自己做了验证:D