【问题标题】:bootstrap class adds by jquery without plugin引导类由 jquery 添加,无需插件
【发布时间】:2017-02-13 23:38:12
【问题描述】:

我正在尝试以引导形式添加一个类以进行验证。这是我的表格

<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>

这是我的 jquery

$(document).ready(function() {
$("#FirstName").focusin(function(){
var is_name = $("input").val();
if(is_name ==='' && is_name === null){
$('div').addClass('has-error');
$('span').addClass('glyphicon-remove');
}
});
});

我希望如果 name 为 null 或为空,它应该在现有类中添加引导类 glyphicon-remove,这与我想在进一步的表单输入中执行此操作的方式完全相同。有人可以帮助我不想使用 jquery 插件我想学习它。我正在使用引导程序 3.3.7 cdn。

谢谢

【问题讨论】:

    标签: javascript jquery html forms twitter-bootstrap-3


    【解决方案1】:

    这样就可以了。

    $(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');
    

    您告诉 jQuery 将“has-error”类添加到页面上的每个 div。

    相反,您可以使用 $(this) 获取对刚刚单击的输入的引用,因此现在您可以将类添加到输入本身。

    你可以使用:

    $(this).addClass('has-error');
    

    但是因为你需要找到'span'标签,你仍然需要对输入的引用,所以最好的做法是使用这行来缓存它:

    var $this = $(this);
    

    现在 jQuery 为输入保存了一个变量,这对性能来说更好。

    最后,使用 jQuery 的 'next' 方法找到 span 标签并为其添加 'glyphicon-remove' 类:

    $this.next('span').addClass('glyphicon-remove');
    

    希望对您有所帮助。

    【讨论】:

    • 谢谢你,克里斯,因为我做了自己的验证:D
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多