使用JSP文档(JSPX)有条件地在元素上设置属性 [英] Conditionally set an attribute on an element with JSP Documents (JSPX)

查看:223
本文介绍了使用JSP文档(JSPX)有条件地在元素上设置属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在HTML表单中,可以通过在按钮上定义"disabled"属性(其值为任意值)来禁用按钮:

In HTML forms, buttons can be disabled by defining the "disabled" attribute on them, with any value:

<button name="btn1" disabled="disabled">Hello</button>

如果要启用按钮,则该属性不应存在,因为没有可以将禁用属性设置为该按钮的启用的已定义值.

If a button is to be enabled, the attribute should not exist as there is no defined value that the disabled attribute can be set to that would leave the button enabled.

在使用JSP文档(jspx)时要启用/禁用按钮时,这给我带来了问题.由于JSP文档必须是格式正确的XML文档,因此我看不到有条件地包含此属性的任何方式,因为以下内容不合法:

This is causing me problems when I want to enable / disable buttons when using JSP Documents (jspx). As JSP documents have to be well-formed XML documents, I can't see any way of conditionally including this attribute, as something like the following isn't legal:

<button name="btn1" <%= (isDisabled) ? "disabled" : "" %/> >Hello</button>

虽然我可以使用JSTL if标签复制标签两次,以获得预期的效果,但在我的特定情况下,我在按钮上声明了15个以上的属性(很多AJAX的javascript事件处理程序属性),因此重复进行标签使JSP非常混乱.

While I could replicate the tag twice using a JSTL if tag to get the desired effect, in my specific case I have over 15 attributes declared on the button (lots of javascript event handler attributes for AJAX) so duplicating the tag is going to make the JSP very messy.

如何在不牺牲JSP可读性的情况下解决此问题?是否有任何可通过处理输出DOM来向父级添加属性的自定义标签?

How can I solve this problem, without sacrificing the readability of the JSP? Are there any custom tags that can add attributes to the parent by manipulating the output DOM?

推荐答案

我使用具有动态属性的自定义JSP标记.您可以这样使用它:

I use a custom JSP tag with dynamic attributes. You use it like this:

<util:element elementName="button" name="btn1" disabled="$(isDisabled ? 'disabled' : '')"/>

基本上,此标签的作用是生成一个带有elementName的XML元素,并将所有属性都放入标签中,但跳过空的属性.

Basically, what this tag does is generate an XML element with elementName and puts all attributes present in the tag, but skips the empty ones.

标签本身非常容易实现,我的实现只有44行.

The tag itself is pretty easy to implement, my implementation is just 44 lines long.

这篇关于使用JSP文档(JSPX)有条件地在元素上设置属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆