16

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

我想实现一个简单的“你确定吗?” 使用 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?
4

4 回答 4

31

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

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

由于它已经返回boolean,因此绝对不需要将其包装在if其他答案建议的 a 中。

于 2010-11-10T20:41:07.583 回答
3

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

<h:commandButton  
    id="commandButtonAcceptDraft" 
    title="#{bundle.tooltipAcceptDraft}"  
    action="#{controller.actionReplaceCurrentReportWithDraft}"  
    onclick="return confirm('Are you sure?')"
    image="/images/checkmark.gif"> 
</h:commandButton> 
于 2010-11-10T20:35:53.207 回答
2

这应该有效。理想情况下,它应该在 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>
于 2010-11-10T20:40:42.993 回答
1

我不确定你必须听什么事件(我假设是 onclick),因为我从未使用过 JSF。一般来说,这应该有效。

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

element.onclick = function(e){
  return confirm('Are you sure etc...');
};
于 2010-11-10T20:25:29.980 回答