javascript - 在循环中设置输入文本的焦点

标签 javascript jsf-2 focus

我需要将焦点设置到组件中的 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/

相关文章:

java - 文件因重音符号而被截断

IE浏览器中的JQuery选择框焦点问题

android - 微调器没有获得焦点

javascript - 将小端十六进制字符串解析为十进制

javascript - 仅在父项上捕获或取消 JS 滚轮事件 - 而不是子项

javascript - Angular Directive(指令) : whats the difference between scope in controller vs scope in link function?

javascript - NodeJS - 如何从 blob 下载?

jsf - 如何在 EL 中获取当前组件的 id

debugging - 如何在 Tomcat 中通过 JNDI 配置 JSF 2.0 应用程序的项目阶段

android - 如何去除返回栈 fragment 的焦点?