【问题标题】:Prevent default action防止默认操作
【发布时间】:2011-06-29 14:42:09
【问题描述】:

此页面在新窗口中打开。 我有一个文本框和两个按钮(h:commandbutton 和 a4j:commandButton)。

我将光标焦点移动(设置)到文本字段中。

我的问题是,我从文本字段中点击输入按钮,然后自动调用 h:comandButton 操作并关闭新窗口。如何避免这种情况。

但是,我需要,当我按下回车键时,将光标焦点移动到 a4j:commandButton

<f:view>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script type="text/javascript">

            function a4jButtonClick()
            {
                alert("A4J Command Buton clicked...");
            }
        </script>

    </head>
    <body>
        <h:form id="sampleForm">
            <rich:panel id="samplePanel">

            <h:outputText value="User Name : "/>
            <h:inputText/>

            <h:commandButton value="Closing-CommandButton" 
                             onclick="javascript:window.close();return false;"/>

            <a4j:commandButton value="A4JCommandButton" onclick="a4jButtonClick()"/>                      

            </rich:panel>
        </h:form>
    </body>
</html>
</f:view>

如果我从文本文件中按回车按钮,我想调用脚本警报(“A4J 命令按钮单击...”);

帮帮我。 提前致谢。

【问题讨论】:

    标签: javascript jsf button command richfaces


    【解决方案1】:

    当您在键盘上按 Enter/Return 时,标记中的第一个按钮被激活。

    因此,您需要将标记中按钮的顺序更改为:

    <a4j:commandButton value="A4JCommandButton" onclick="a4jButtonClick()"/>
    <h:commandButton value="Closing-CommandButton" onclick="javascript:window.close();return false;"/>
    

    请记住,您仍然可以为它们设置样式以保持原始顺序,这样设计就不会改变。

    【讨论】:

      【解决方案2】:

      尝试在 onclick 处理程序中添加 return false:

      <h:commandButton value="HCommandButton" onclick="hButtonClick();return false;"/>
      <a4j:commandButton value="A4JCommandButton" onclick="a4jButtonClick();return false;"/>
      

      但是当你按下按钮时你的表单将不会被提交。

      【讨论】:

      • 感谢您的回复。现在我更新我的问题。我使用返回错误。即使窗口关闭了。
      • 当然是关闭了,window.close()在return false之前调用了:)
      • 好的。首先我使用 onclick"return false;javascript:window.close();"。但是如果我手动点击“Closing-CommandButton”,新窗口不会关闭。
      • 您要关闭窗口吗?或者你想阻止按钮动作?如果您想阻止表单提交 - 在 onclick 结束时返回 false 必须对您有所帮助。
      • 如果我点击关闭按钮,那么我需要关闭窗口。问题是,在文本字段中设置光标点。现在点击键盘上的回车键,那个时间窗口会自动关闭。无需自动关闭。手动我单击关闭按钮,然后关闭 winwow。