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

Jim*_*ugh 13 javascript java jsf myfaces

在我的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>
Run Code Online (Sandbox Code Playgroud)

解:

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

<f:loadBundle basename="com.jimtough.resource.LocalizationResources" var="bundle" />
Run Code Online (Sandbox Code Playgroud)

<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>
Run Code Online (Sandbox Code Playgroud)

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

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

Bal*_*usC 26

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

<h:commandButton onclick="return confirm('Are you sure?')" />
Run Code Online (Sandbox Code Playgroud)

因为它已经返回boolean,所以绝对不需要在if其他答案的建议中包装它.