javascript 如何根据参数值在jsp文件中使用动态css

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14775958/
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-10-26 22:32:30  来源:igfitidea点击:

how to use dynamic css in jsp file base on param value

javajavascriptcssjsp

提问by Mina

I have a jsp file ,like this :

我有一个jsp文件,像这样:

<html>
<head>
     <script type="text/javascript">
       var type=<bean:write name="class" property="type" />  
     </script> 

     <style type="text/css">
        .td-type1
        {
            width: 10mm;
        }
        .td-type2
        {
            width: 20mm;
        }
    </style>
</head>
<body>
    <table>
        <tr>
            <td class="td-type1">
            </td>
        </tr>
    </table>
</body>
</html>

My question is: How to change css dynamically base on type value? For example, if type equal 2, then the css class of td-type2 should be used for td tag. should I use .properties file to save all config or multi css files or ...?

我的问题是:如何根据类型值动态更改 css?例如,如果 type 等于 2,那么 td-type2 的 css 类应该用于 td 标签。我应该使用 .properties 文件来保存所有配置或多个 css 文件还是...?

回答by Xavi López

You can append the request attribute's value to the classattribute in the JSP :

您可以将请求属性的值附加到classJSP 中的属性:

<td class="td-type<%=type%>">

As a side note, the use of scriptlets (java code in JSP's) is strongly discouraged. Use JSTL and EL instead. In this question you'll find out Why and how to avoid Java Code in JSP files.

作为旁注,强烈建议不要使用 scriptlet(JSP 中的 Java 代码)。请改用 JSTL 和 EL。在这个问题中,您将了解为什么以及如何避免在 JSP 文件中使用 Java 代码

<td class="td-type${type}">

Or, if you wanted to implement an if-else like construct, for instance :

或者,如果您想实现类似 if-else 的构造,例如:

<c:choose>
    <c:when test="${type eq "2"}">
        <c:set var="varclass" value="td-type2"/>
    </c:when>
    <c:otherwise>
        <c:set var="varclass" value="td-type1"/>
    </c:otherwise>
</c:choose>
<td class="${varClass}">