这个问题在这里已经有答案了:

如果您有 JSF <h:commandLink> (它使用 onclick 事件的 <a> 提交当前表单),在执行操作之前如何执行 JavaScript(例如要求删除确认)?

有帮助吗?

解决方案 2

<h:commandLink id="myCommandLink" action="#{myPageCode.doDelete}">
    <h:outputText value="#{msgs.deleteText}" />
</h:commandLink>
<script type="text/javascript">
if (document.getElementById) {
    var commandLink = document.getElementById('<c:out value="${myPageCode.myCommandLinkClientId}" />');
    if (commandLink && commandLink.onclick) {
        var commandLinkOnclick = commandLink.onclick;
        commandLink.onclick = function() {
            var result = confirm('Do you really want to <c:out value="${msgs.deleteText}" />?');
            if (result) {
                return commandLinkOnclick();
            }
            return false;
        }
    }
}
</script>

其他 Javascript 操作(例如验证表单输入等)可以通过替换调用来执行 confirm() 调用另一个函数。

其他提示

可以这样简化

onclick="return confirm('Are you sure?');"

这对我有用:

<h:commandButton title="#{bundle.NewPatient}" action="#{identifController.prepareCreate}"  
                                             id="newibutton" 
                                             onclick="if(confirm('#{bundle.NewPatient}?'))return true; else return false;" 
                                             value="#{bundle.NewPatient}"/>

您仍然可以使用 onclick。JSF 渲染套件规格 (请参阅编码行为)描述了链接应如何处理它。这是重要的部分(它为 onclick 呈现的内容):

var a=function(){/*your onclick*/}; var b=function(){/*JSF onclick*/}; return (a()==false) ? false : b();

因此,您的函数不会传递事件对象(无论如何,跨浏览器都不可靠),但返回 true/false 会短路提交。

在 JSF 1.2 中,您可以指定 onclick 事件。

此外,其他库例如 我的面孔 或者 冰面 实现“onclick”处理程序。

那么你需要做的很简单:

<h:commandLink action="#{bean.action}" onclick="if(confirm('Are you sure?')) return false;" />

笔记:你不能只是这样做 return confirm(...) 因为这将阻止 onClick 事件中其余 JavaScript 的发生,这将有效地阻止您的操作发生,无论用户返回什么!

如果您想在表单发布之前执行某些操作(例如进行确认),请尝试表单事件 onSubmit。就像是:

myform.onsubmit = function(){confirm("really really sure?")};

这对我来说从来没有用过

 onclick="if(confirm('Are you sure?')) return false;" />

但这确实

onclick="if(confirm(\"Are you sure?\"))return true; else return false;"
var deleteClick;
var mess="xxx";
function assignDeleteClick(link) {
    if (link.onclick == confirmDelete) {
        return;
    }
    deleteClick = link.onclick;
    link.onclick = confirmDelete;
}


function confirmDelete() {
    var ans = confirm(mess);
    if (ans == true) {
        return deleteClick();
    } else {
        return false;
    }
} 

将此代码用于 jsf 1.1。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top