如何使用 jquery 显示或隐藏标签

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27884147/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:28:07  来源:igfitidea点击:

How to show or hide a label using jquery

jquerycsshtmltwitter-bootstrap-3

提问by A NewBie

I have the following code.

我有以下代码。

<div class="form-group">
            <label class="col-sm-2 control-label labelfont">FIRST NAME:</label>
            <div class="col-sm-6">
               <input type="text" class="form-control" placeholder="Enter the First Name" id="FirstName">
            </div>
            <label class="col-sm-2 labelfont errorMsg" id="Err_FirstName">Enter the first name</label>
        </div>

Initially "Err_FirstName"is hidden.If the input field is empty on tabout,I want the error labelto be displayed.

最初"Err_FirstName"是隐藏的。如果标签上的输入字段为空,我希望error label显示。

I have written the following code in blur event.

我在模糊事件中编写了以下代码。

$("#FirstName").on("blur", function () {
    if ($(this).val().trim().length == 0) {
        $("#Err_FirstName").show();
    }
    else {
        $("#Err_FirstName").hide();
    }
});

the 'errormsg'class is defined as

所述'errormsg'类被定义为

.errorMsg {
   display:none;        
   color:Red;
}

The label is not getting displayed on tabout.Could someone point me in the right direction,in case I am doing something wrong.

标签没有显示在 tabout 上。有人可以指出我正确的方向,以防我做错了什么。

回答by Ragini Gurram

The code perfectly works for me. JSFiddle.

该代码非常适合我。JSFiddle

$("#FirstName").on("blur", function () {
    if ($(this).val().trim().length == 0) {
        $("#Err_FirstName").show();
    }
    else {
        $("#Err_FirstName").hide();
    }
});
.errorMsg {
   display:none;        
   color:Red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="form-group">
            <label class="col-sm-2 control-label labelfont">FIRST NAME:</label>
            <div class="col-sm-6">
               <input type="text" class="form-control" placeholder="Enter the First Name" id="FirstName">
            </div>
            <label class="col-sm-2 labelfont errorMsg" id="Err_FirstName">Enter the first name</label>
        </div>

May be worth checking jQuery version you are using .for this code snippet i am using jQuery 1.9.1 .The Best practice to do this is having another class and change the class name if there is no value in the FirstName.

可能值得检查您正在使用的 jQuery 版本。对于此代码片段,我使用的是 jQuery 1.9.1。执行此操作的最佳实践是拥有另一个类并在 FirstName 中没有值时更改类名。