我尝试将内部JS代码放入JS块中。这应该通过h:commandButton
的自定义渲染器来完成。Renderer是入站的,可以找到。但是一旦我开始生成脚本块,它被放在<!--
和-->
之间。
下面是生成脚本块的方法:
private void writeScript(FacesContext ctx, HtmlCommandButton button, String event, String script) throws IOException {
String nonce = UUID.randomUUID().toString();
ResponseWriter writer = ctx.getResponseWriter();
ctx.setResponseWriter(writer);
writer.startElement("input", button);
writer.writeAttribute("type", "submit", null);
writer.endElement("input");
writer.startElement("script", button);
writer.writeAttribute("nonce", nonce, null);
writer.write("document.getElementById('" + button.getClientId()
+ "')."
+ event
+ " ="
+ " function() {"
+ script
+ "}");
writer.endElement("script");
}
同样使用startCDATA()
方法似乎不起作用。
所以不是:
<script nonce="...">
document.getElementById('j_id1955899975_7494aa2f:submitButton').alert('hallo') = function() {onclick}
</script>
生成的代码如下:
<script nonce="...">
<!--
document.getElementById('j_id1955899975_7494aa2f:submitButton').alert('hallo') = function() {onclick}
//-->
</script>
我做错了什么?如果有人能帮我,那就太好了:D
根据Predrag Maric的链接,我将代码更改为:
private void writeScript(FacesContext ctx, HtmlCommandButton button, String event, String script) throws IOException {
System.out.println("das event: "+event);
String nonce = UUID.randomUUID().toString();
ResponseWriter writer = ctx.getResponseWriter();
ctx.setResponseWriter(writer);
writer.startElement("input", button);
writer.writeAttribute("type", "submit", null);
writer.writeAttribute("id", button.getClientId(), null);
writer.endElement("input");
writer.write("<script>");
writer.write("document.getElementById('" + button.getClientId()
+ "')."
+ event
+ " ="
+ " function() {"
+ script
+ "}");
writer.write("</script>");
}
问题是用ResponseWriter
的writeElement()
方法编写脚本标签它会自动添加注释…在编码之后,它可以工作了,非常感谢!