我需要将焦点设置到组件中的 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,然后显示在被点击的行下方,并允许用户输入一个数字并让服务器处理它。)
最佳答案
document.getElementById()
需要生成的 HTML 客户端 ID,而不是 JSF 组件 ID。您需要在浏览器中打开该页面,右击并查看源代码 自己查看。找到生成的 HTML <input>
<p:inputText>
的元素并使用它的 id
.此 ID 前面加上每个父级的组件 ID NamingContainer
组件如 <h:form>
, <h:dataTable>
, <p:tabView>
等
您似乎在使用 PrimeFaces。您可以使用 p:component()
EL 函数打印给定组件 ID 的客户端 ID。
<script>document.getElementById("#{p:component('amountInput')}").focus()</script>
如果您不使用 PrimeFaces,另一种方法是将组件绑定(bind)到 View 并使用 UIComponent#getClientId()
.
<h:inputText id="amountInput" binding="#{amountInput}" value="#{bean.bidAmount}" />
...
<script>document.getElementById("#{amountInput.clientId}").focus()</script>
回到 PrimeFaces,你知道 the <p:focus>
component 吗? ?您也可以使用它。
<h:panelGroup id="bidView">
<p:focus context="bidView" />
...
</h:panelGroup>
关于javascript - 在循环中设置输入文本的焦点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9410667/