Primefaces p:menuitem 不会在 onclick 事件 return true 时触发事件

Primefaces p:menuitem don't fire event when onclick event return true

我正在使用 PrimeFaces p:menuitem 组件执行删除。为了添加确认步骤,我使用了显示 JavaScript 确认对话框的 onclick 事件。在我的代码下方:

<p:menuitem icon="fa fa-fw fa-remove"
    title="#{message.global_remove}"
    value="#{message.global_remove}"
    actionListener="#{componentListMB.delete(cp.id)}"
    onclick="return confirm('#{message.component_list_confirm_deletion}')"
    update=":component_list" />

当用户确认删除时不会触发该操作,而是在 URL 的末尾添加 #

为什么在 p:commandButton 一切正常时事件没有被触发?


我正在使用:

您可以使用 <p:menuitem> 中的 <p:confirm> 进行确认。

编辑:只需删除 confirm() 之前的 return 并且所有内容也应该按预期工作。

您可以尝试将 <p:menuitem> actionListener 委托给 <p:commandButton>。然后在 <p:commandButton> 中嵌套一个 <p:confirm> 作为您的确认消息。然后通过 <p:menuitem>onclick 属性触发命令按钮。

Using confirm() without return does not resolve the problem. Instead, it submits the form even when the confirmation dialog is cancelled. I want to know if there is any workaround using onclick event before using

您应在确认对话框中的取消按钮上重置值,或者您应在页面加载时获取新数据。

使用 p:confirmDialog:

<p:menuitem icon="fa fa-fw fa-remove"
    title="#{message.global_remove}"
    value="#{message.global_remove}"
    onclick="PF('confirm').show();"/>

<p:confirmDialog widgetVar="confirm"
     message="#{message.component_list_confirm_deletion}">
    <p:commandButton value="Confirm"
            oncomplete="PF('confirm').hide();" update=":component_list"
            action="#{componentListMB.delete(cp.id)}" />
    <p:commandButton value="Cancel"
            onclick="PF('confirm').hide();" />  </p:confirmDialog>

The action is not fired when the user confirm the deletion but, instead, a # is added at the end of the URL.

Primefaces 实际上是将您的 p:menuitem 呈现为 a HTML 标记,使用元素的 onclick 事件执行它自己的 Ajax 请求.例如

onclick="PrimeFaces.ab({...});return false;"

请注意,他们在 a 元素的 which prevents the default browser behaviour 末尾添加了一个 return false;,因此 # 不会出现在 URL 中。

添加confirm函数时,它被放置在onclick元素的开头,如下所示:

onclick="return confirm('confirm?');PrimeFaces.ab({...});return false;"

如果您不确认,# 将不会出现在 URL 中,因为默认行为已被阻止。如果你确认它会出现。但是 Ajax 操作将永远不会执行,因为您首先调用了 return 语句。

您可以通过更改 p:menuitemonclick 事件实现预期的行为,如下所示:

onclick="if (!confirm('#{message.component_list_confirm_deletion}')) return false;"

Why the event is not fired while in a p:commandButton everything works fine ?

Primefaces 对待 p:commandButton 的方式不同。它包装了用户的 onclick 和 Primefaces Ajax 函数,将它们中的每一个都放在一个单独的函数中,然后将它们发送到 Primefaces#bcn,后者按顺序执行这些函数。第一个 returns false 停止其余函数的处理。生成的HTML中的onclick将如下所示:

onclick="PrimeFaces.bcn(this, event, [function(event){return confirm('confirm?')},function(event){PrimeFaces.ab({...});return false;}]);"