繁体   English   中英

JSF - 如何为<h:commandButton>实现JavaScript“你确定吗?”提示

[英]JSF - How do I implement a JavaScript “Are you sure?” prompt for a <h:commandButton>

在我的JSF 1.2 webapp中,我有一个带有<h:commandButton>的页面,它调用辅助bean上的action方法。 此操作将导致数据库中的数据被删除/替换,因此我希望避免用户意外单击命令按钮的任何情况。

我想实现一个简单的“你确定吗?” 使用JavaScript提示“是/否”或“确定/取消”选项。 我对JavaScript并不擅长,之前我从未将JavaScript与JSF混合在一起。 任何人都可以提供代码片段来向我展示如何实现这一点吗?

这是我的JSP页面的一部分,我在其中声明了命令按钮:

<h:commandButton 
    id="commandButtonAcceptDraft"
    title="#{bundle.tooltipAcceptDraft}" 
    action="#{controller.actionReplaceCurrentReportWithDraft}" 
    image="/images/checkmark.gif">
</h:commandButton>

解:

BalusC提供的解决方案运作得很好。 我还想提一下,使用资源包中的文本作为提示文本很容易。 在我的页面上,我使用如下元素加载资源包:

<f:loadBundle basename="com.jimtough.resource.LocalizationResources" var="bundle" />

<f:loadBundle>必须位于<f:view> 然后我将BalusC提供的代码添加到我的命令按钮元素中,但用我的资源包中的字符串替换'你确定吗?' 文字,像这样:

<h:commandButton 
    id="commandButtonAcceptDraft"
    title="#{bundle.tooltipAcceptDraft}" 
    action="#{controller.actionReplaceCurrentReportWithDraft}" 
    image="/images/checkmark.gif"
    onclick="return confirm('#{bundle.confirmationTextAcceptDraft}')">
</h:commandButton>

我的英文资源文件中的行(只是一个带键/值对的纯文本文件)如下所示:

# text displayed in user prompt when calling confirm()
confirmationTextAcceptDraft=This will overwrite the current report and cannot be undone. Are you sure?

使用JavaScript confirm()函数。 它返回一个boolean值。 如果返回false,则按钮的默认操作将被阻止,否则将继续。

<h:commandButton onclick="return confirm('Are you sure?')" />

因为它已经返回boolean ,但绝对没有必要将其套在if一个由其他答案建议。

您可以将javascript添加到按钮的onclick中。

<h:commandButton  
    id="commandButtonAcceptDraft" 
    title="#{bundle.tooltipAcceptDraft}"  
    action="#{controller.actionReplaceCurrentReportWithDraft}"  
    onclick="return confirm('Are you sure?')"
    image="/images/checkmark.gif"> 
</h:commandButton> 

这应该工作。 理想情况下,它应该在java脚本文件中。

<h:commandButton 
    id="commandButtonAcceptDraft"
    title="#{bundle.tooltipAcceptDraft}" 
    action="#{controller.actionReplaceCurrentReportWithDraft}" 
    image="/images/checkmark.gif"
     onclick="if (!confirm('Are you sure?')) return false">
</h:commandButton>

因为我从未使用过JSF,所以我不确定你要听哪个事件(onclick我会假设)。 一般来说,这应该工作。

var element = document.getElementById('commandButtonAcceptDraft');

element.onclick = function(e){
  return confirm('Are you sure etc...');
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM