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

查看:15
本文介绍了有条件地在具有 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天全站免登陆