javascript - 无需服务器往返即可动态启用/禁用表单组件

标签 javascript wicket

我正在创建一个表单,其中只有选中某个复选框时才应启用某些文本字段。

我是 Wicket 的新手,我对以下内容感到好奇:

  1. 我是否可以使用现有的 Wicket 类启用/禁用该字段而无需 (AJAX) 往返服务器? IE。是否可以向字段添加行为,从而导致呈现的 HTML 包含启用/禁用字段的 JavaScript?

  2. 如果上述问题的答案是:我自己在标记中添加所需的 JavaScript 代码是否“合法”?或者我是否冒着弄乱表单提交的风险,以至于它无法被 Wicket 正确识别?

我是 Wicket 的新手,我不确定这里的最佳实践是什么。也许执行此操作的 Wicket 方式总是涉及 AJAX 往返?

最佳答案

Can I enable/disable the field without an (AJAX) round-trip to the server using existing Wicket classes? I.e. is it possible to add behaviors to the fields which causes the rendered HTML to include JavaScript that enables/disables the fields?

是的,您可以在没有服务器往返的情况下做到这一点。不,不是 Wicket 提供的类,您必须自己创建它。这是您可以添加到组件的行为。如果单击具有此行为的组件,则将通过 javascript 禁用构造函数中传递的目标组件:

public class DisableFormComponentBehavior extends Behavior {

private Component sourceComponent;

private FormComponent targetComponent;

public DisableFormComponentBehavior(FormComponent targetComponent) {
    targetComponent.setOutputMarkupId(true);
    this.targetComponent = targetComponent;
}

public void bind(Component component) {
    super.bind(component);
    component.setOutputMarkupId(true);
    this.sourceComponent = component;
}

@Override
public void renderHead(Component component, IHeaderResponse response) {
    super.renderHead(component, response);
    response.render(JavaScriptHeaderItem
            .forReference(JQueryResourceReference.get()));
    response.render(OnDomReadyHeaderItem.forScript(String
            .format("$('#%s').click(function(){$('#%s').prop('disabled', true);});",
                    component.getMarkupId(), targetComponent.getMarkupId())));
}

}

If the answer to the above question is no: Is it "legal" for me to add the required JavaScript code myself in the markup? Or do I run the risk of messing up the form submission so that it is not properly recognized by Wicket?

好吧,上述问题的答案不是“不”,但是将您自己的 javascript 添加到 Wicket html 文件中仍然是完全合法的。但是,您必须在 HTML 中定义组件的 ID。不过,我更喜欢带有行为的解决方案,因为它的可重用性更高。

关于javascript - 无需服务器往返即可动态启用/禁用表单组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17599803/

相关文章:

java - Wicket:如何将 DropDownChoice 与 PropertyModel 一起使用?

java - Wicket,如何在单击时延迟加载 DropDown 选择?

javascript - 使用nodejs和angularjs更新mongodb

javascript - AngularJS Post 请求在 Firefox 上无法正常工作

php - 如何让一个php函数等到脚本结束才执行

java - 如何避免在 wicket 请求结束时重置 FileUploadField

javascript - 为什么 node.js 中的 response.write 不注入(inject) html?

javascript - 如何设置日历应用程序的开始日期

javascript - Wicket 口和 AJAX : Upload file to server and show it on page

java - Wicket:如何实现未分组的单选按钮