[英]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.