如何在单击 JSF 按钮时调用 JS 函数并阻止页面重新加载/导航? [英] How to call JS function on click of JSF button and block page reload/navigation?

查看:40
本文介绍了如何在单击 JSF 按钮时调用 JS 函数并阻止页面重新加载/导航?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用JSF创建按钮调用JS函数的首选方式是什么?

What is the preferred way to create a button with JSF to call JS function ?

实际上我使用:

<p:button onclick="myJSFunction();" href="#"/>

但我的网址后缀为锚符号(#).

but my urls are suffixed with the anchor symbol (#).

是否有另一种推荐的方法来创建不会重新加载/导航到 URL 而是调用 JS 函数的按钮?

Is there another recommended way to create button which will not reload/navigate to URL but call JS function please ?

推荐答案

那是因为它实际上导航到 #.您需要阻止按钮执行其默认操作,即导航到当前视图或 hrefoutcome 中指定的 URL.您可以通过在 onclick 的末尾添加 return false; 来实现这一点.

That's because it's actually navigating to #. You need to block the button from performing its default action, which is navigating to the current view, or to the URL as specified in href or outcome. You can achieve this by adding return false; to the end of onclick.

<p:button onclick="myJSFunction(); return false;" />

或者,如果 myJSFunction() 实际上返回一个 boolean 来确定按钮是否应该继续其默认操作,然后委托给它:

Or, if myJSFunction() actually returns a boolean which should determine if the button should continue its default action, then delegate to it:

<p:button onclick="return myJSFunction();" />

<h:button> 的工作方式完全相同,只是在标准外观中.

The <h:button> works exactly the same way, it's only in standard look'n'feel.

另一种方法是使用 <p:commandButton type="button">,它生成一个真正的 <input type="button">任何导航.这样你就不需要从 onclick 返回 false.

An alternative is to use <p:commandButton type="button">, which generates a real <input type="button"> without any navigation. This way you don't need to return false from onclick.

<p:commandButton type="button" onclick="myJSFunction()" />

然而,这需要一个 (尽管将它放在任何表单之外不会破坏任何功能).这同样适用于 .

This however requires a <h:form> (although placing it outside any form doesn't break any functionality). The same applies to <h:commandButton>.

这篇关于如何在单击 JSF 按钮时调用 JS 函数并阻止页面重新加载/导航?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆