从输入标记调用CSS样式文件

时间:2016-01-05 14:26:21

标签: html css jsp

我在客户端创建一个表单,有一个JSP页面,在服务器端我使用Java servlet来处理数据。我想要做的是,如果有错误,我希望能够传递一条错误消息,这将导致输入在其下面获得一条红线表示错误。我的代码完美无缺:

<input type="email" name="email" id="email" value="${param.email}" class="validate" <c:if test="${ not empty emailError}">style="border-bottom: 2.5px solid red; "</c:if>>
<label for="email" data-error="${emailError }" data-success="">Email</label>

我想知道的是,有没有办法删除style="border-bottom: 2.5px solid red; "并用css文件替换它。我想这样做的原因是因为我将拥有数百行具有该特定样式的代码,如果我想将样式更改为其他内容我需要遍历每个页面并逐行替换所有内容。那么我可以将这个样式存储在一个单独的文件中,只需调用该文件来创建相同的效果吗?我这样做是为了便于维护。

我还想注意,我不能只将它添加到样式表中,因为所有输入都会在它们下面有一条红线,我只希望输入在出现错误时显示红线用那个具体的输入。

2 个答案:

答案 0 :(得分:3)

我不确定你的JSP方式,检查代码的正确性。我只想做的是:

  1. 创建一个名为.error的CSS类,并使用{border-bottom: 2px solid red;}对其进行定义。请注意,px is always integer
  2. 其次,我将使用AJAX返回任何数据以验证它们。
  3.   

    注意: ps:抱歉,我使用的是jQuery library,这太棒了,你还没有在你的OP中说过。< / em>的

    让我告诉你一个简单的方法:

    $(function () {
      $("#numcheck").keyup(function () {
        $this = $(this);
        $.post("/path/to/check.jsp", function (res) {
          if (res != "OK")
            $this.addClass("error");
          else
            $this.removeClass("error");
        });
      });
    });
    * {font-family: 'Segoe UI';}
    .error {border-bottom: 2px solid red;}
    <script src="https://code.jquery.com/jquery-1.11.3.js"></script>
    <input type="text" id="numcheck" />

答案 1 :(得分:1)

Praveen Kumar非常了解创建.error课程。我最终做的是:

<input type="email" name="email" id="email" value="${param.email}" class="validate" onclick="inputClicked('email')">
<label for="email" data-error="${emailError }" data-success="">Email</label>

<c:if test="${ not empty emailError}">
   <script type="text/javascript">
        javascript:error('email');
    </script></c:if>

和Javascript错误(...)方法:

<script>
window.error = function(name) {

  document.getElementById(name).style.borderBottom = "solid red";
}
</script> 

删除样式:

<script>

function inputClicked(name){
      $("#"+name).removeAttr("style")
};
</script>