无法使用Javascript添加Class

Unable to addClass using Javascript

本文关键字:添加 Class Javascript      更新时间:2023-09-26

我想通过在验证时(即在提交时)添加一个类来对所有空文本框进行样式设置,但我的代码不起作用。不确定是脚本还是自定义验证器。我只想使用JS。如果我说

target.style.border="1px solid red";

不过它起作用了。只是无法添加类。

JS:

<link href="StyleSheet.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
 function validateTextBox(sender, args) {
        var target = document.getElementById(sender.controltovalidate);
        var is_valid = target.value != "";
        if (is_valid) {
            target.removeClass("validate");
        }
        else {
            target.addClass("validate");
        }
        args.IsValid = is_valid;
    } 
</script>      

ASPX:

 <asp:TextBox ID="txtSurname" runat="server"></asp:TextBox>
 <asp:CustomValidator ID = "CustomValidator1" runat="server" 
 ControlToValidate="txtSurname" ValidateEmptyText="true" 
 ClientValidationFunction="validateTextBox"
 ></asp:CustomValidator>

CSS:

 .validate
 {
   border:2px solid red;
 }

document.getElementById返回一个DOM元素,该元素没有addClass或removeClass API。

参见:元件

要应用类,请尝试(提出想法,请根据确切的业务逻辑进行调整):

target.className = target.className + " validate"

如果我们使用原始JS,我们必须编写原始代码,并忘记addClass或removeClass:-)要删除类,请参见以下答案:使用javascript 删除类

试试这个。简单的方法。

function validateTextBox() {
        var target = document.getElementById("#<%= txtSurname.ClientID %>");
        **var is_valid = target.value;**
        **if (is_valid!="") {**
            target.removeClass("validate");
              **return true;**
        }
        else {
            target.addClass("validate");
            **return false**
        }
    } 

ASPX:

 <asp:TextBox ID="txtSurname" runat="server"></asp:TextBox>
 <asp:CustomValidator ID = "CustomValidator1" runat="server" 
 ControlToValidate="txtSurname" ValidateEmptyText="true" 
 ClientValidationFunction=**"Javascript:return validateTextBox()"**
 ></asp:CustomValidator>

也许您想使用jquery验证插件?这是一个广泛使用的插件。

<asp:TextBox ID="txtSurname" runat="server" CssClass="toValidate"></asp:TextBox>
jQuery(function() {
    // You can specify some validation options here but not rules and messages
    jQuery('form').validate(); 
    // Add a custom class to your name mangled input and add rules like this
    jQuery('.toValidate').rules('add', { 
        required: true
    });
});

此代码应在表单提交前检查文本框是否为空。

更改var target = document.getElementById(sender.controltovalidate.ClientID);

至:var target = document.getElementById(sender.ClientID);

试试这个。。。

function validateTextBox(sender, args) {
        var target = document.getElementById(sender.controltovalidate.ClientID);
        if (target.value != "") {
            target.removeClass("validate");
        }
        else {
            target.addClass("validate");
        }
        args.IsValid = "";
    }