【问题标题】:Setting focus of input text in a loop在循环中设置输入文本的焦点
【发布时间】:2012-02-23 09:54:21
【问题描述】:

我需要将焦点设置为 h:inputText,它位于这样的组件中:

    <h:panelGroup id="bidView">
        <h:panelGroup rendered="#{some conditions}">            
            <h:outputText>
            Some text</h:outputText>                
            <p:inputText id="amountInput" value="#{bean.bidAmount}" />
            <h:commandButton value="Submit">
                <f:ajax listener="#{bean.submit(item)}" execute="@form" render="bidView "/>
            </h:commandButton>
        </h:panelGroup>
            <script>document.getElementById('amountInput').focus()</script>

    </h:panelGroup>

需要获得焦点的输入文本是“amountInput”。我认为应该这样做的javascript代码是

<script>document.getElementById('amountInput').focus()

但它会生成以下错误:“Cannon call method 'focus' of null。”我错过了什么?

(我应该补充一点,当用户单击表格内每一行旁边的提交按钮时,会呈现bidView。它,bidView,然后显示在该单击的行下方,并允许用户输入一个数字并让服务器处理它。)

【问题讨论】:

  • 您的bidView 是否由&lt;h:form&gt; 包装?如果是,很可能所有组件的 id 中都会有该后缀。例如:。你能检查一下萤火虫并确保客户端ID是完整的吗?
  • 是的,它被包裹在一个表单中。我给了它一个 id,“theform”,我试图使用 theform:j_id_2l:19:bidView:amountInput 访问组件(j_id_21 也附加到每个组件,19 代表循环中的位置)但它仍然无效的。那是正确的方法吗,尝试关闭所有组件? JSF 不知道如何找到命名组件吗?
  • 这很奇怪。 document.getElementById('theform:j_id_2l:19:bidView:amountInput').focus() 应该可以工作。 AFAIK,这是一种完全有效的方法。关于您的另一个问题,每个组件库都有自己的客户端 javascript API。由于您使用的是primefaces,我建议您通过他们的客户端API,这可能允许您访问没有前缀的组件(我无法确定,因为我没有使用过primefaces)
  • 你提到了一个循环。这是否意味着每一行都有一个 bidView 实例?因为如果是这种情况,您将无法硬编码 19
  • @Nikhil:&lt;h:panelGroup&gt; 不是NamingContainer,所以bidView 肯定不应该出现在输入组件的客户端ID 中。

标签: javascript jsf-2 focus


【解决方案1】:

document.getElementById() 需要生成的 HTML 客户端 ID,而不是 JSF 组件 ID。您需要在浏览器中打开该页面,然后右键单击并查看源代码 以自己查看。找到&lt;p:inputText&gt; 的生成的HTML &lt;input&gt; 元素并准确使用它的id。此 ID 前面带有每个父组件的组件 ID NamingContainer,例如 &lt;h:form&gt;&lt;h:dataTable&gt;&lt;p:tabView&gt; 等。

您似乎在使用 PrimeFaces。您可以使用p:component() EL 函数打印给定组件 ID 的客户端 ID。

<script>document.getElementById("#{p:component('amountInput')}").focus()</script>

如果您没有使用 PrimeFaces,另一种方法是将组件绑定到视图并使用 UIComponent#getClientId()

<h:inputText id="amountInput" binding="#{amountInput}" value="#{bean.bidAmount}" />
...
<script>document.getElementById("#{amountInput.clientId}").focus()</script>

回到 PrimeFaces,你知道the &lt;p:focus&gt; component 吗?你也可以使用它。

<h:panelGroup id="bidView">
    <p:focus context="bidView" />
    ...
</h:panelGroup>

【讨论】:

  • 谢谢你,BalusC。 对我有用。我知道 JSF2 太优雅了,不能没有这样的东西。
  • 您也可以使用 PrimeFaces Javascript API:PrimeFaces.focus(id,context)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-30
  • 1970-01-01
相关资源
最近更新 更多