我询问了这个Is it possible to add a javascript function to a h:form in jsf2?,但是它被关闭为一个副本,并有一个指向这个https://stackoverflow.com/a/29129816/4142984答案的链接。
也许在我的问题中,我没有清楚地说明我想做什么:我想要一个复合,其内部结构在未来的版本中可能会发生变化。我希望这个复合具有一个javascript函数,可以从外部调用这个函数来处理所有内部细节,这些内部细节封装在复合内部,外部没有代码的任何部分。
<h:form onload="this.myfunc=function(){alert('Hello world');}" ...
可以做到这一点,但是h:form没有"onload“。
这样,当组合的结构发生变化时,就不需要更改使用复合的页面。
所谓的答案有两部分。标签为“2.”的部分根本不回答我的问题,因为它需要复合外部的javascript。
标签为“1.”的部分看上去好多了,但我没法让它起作用。
我将以下内容放在我的复合材料的h:表单中:
<h:outputScript>alert("Now"+this+'#{cc.attrs.imgId}');window.document.getElementById('#[cc.attrs.imgId}').myfunc=function() {alert("newly called"+#{mBean.keyX})}</h:outputScript>
但这失败了。首先,“这”是窗口,不是我的“形式”。其次,getElementById没有找到元素,这显然是因为id是由jsf更改的。
那我该怎么做才能让它起作用呢?
编辑:由于提示和答案,下面的代码可以工作:
<composite:implementation>
<h:form id="${cc.attrs.imgId}" styleClass="small">
<f:event type="postAddToView" listener="#{mBean.register}" />
<f:attribute name="myId" value="hmta${cc.attrs.imgId}" />
<h:graphicImage width="${cc.attrs.width}" id="${cc.attrs.imgId}"
onclick="this.nextSibling.value=mods(event)" onmouseover="aa=this.id"
value="images/img?#{cc.attrs.flav}=#{Math.random()}">
<f:ajax event="click" execute="@this k"
listener="#{mBean.handleEvent}" render="@this">
</f:ajax>
</h:graphicImage>
<h:inputHidden id="k" value="#{mBean.keyX}" />
</h:form>
<h:outputScript>window.document.getElementById('#{cc.clientId}:#{cc.attrs.imgId}').myfunc=function() {alert("newly called"+#{mBean.keyX})};</h:outputScript>
</composite:implementation>
发布于 2016-01-16 18:52:09
第一
通过提供ID来调用复合组件:
<core:yourComposite id="someId" .../>
第二
在h:form属性上添加prependId=false
以防止自动ids,并为该表单提供id
现在检查呈现的html,您将看到具有映射语义id (如:someId:formId
)的表单,现在您可以在表单调用中注入脚本:
getElementById('#{cc.attrs.id}:formId')
非常正常
https://stackoverflow.com/questions/34827840
复制相似问题