我想使用JavaScript来操作JSF / Facelets页面中的隐藏输入字段。当页面加载时,我需要为客户端的颜色深度设置一个隐藏字段。

来自我的Facelet:

<body onload="setColorDepth(document.getElementById(?????);">

<h:form>
  <h:inputHidden value="#{login.colorDepth}" id="colorDepth" />
</h:form>

当JSF处理页面时,它当然会更改元素的ID。从我的JavaScript代码中引用这些元素的最佳方法是什么?

有帮助吗?

解决方案

您需要设置表单的ID,以便您知道它是什么。然后,您将能够构造实际的元素ID。

<body onload="setColorDepth(document.getElementById('myForm:colorDepth');">

<h:form id="myForm">
  <h:inputHidden value="#{login.colorDepth}" id="colorDepth" />
</h:form>

如果您不想设置表单的ID字段,可以在运行时找到它,如下所示:

<body onload="setColorDepth(document.getElementById(document.forms[0].id + ':colorDepth');">

其他提示

查看生成的html源代码,查看jsf命名标记的id属性。

您很快就会看到命名约定的工作原理。它通常像FORMNAME:FIELDNAME

全局定义函数findElement并在任何地方使用它

function findElement(elementId) {
        if(document.getElementById(elementId)) return elementId;
        for(var  i = 0; i < document.forms.length; i++) {
            if(document.getElementById(document.forms[i].id + ':' + elementId)) {
                return document.forms[i].id + ':' + elementId;
            }
        }
        return null;
    }


    <body onload="setColorDepth(findElement('colorDepth'));">
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top