Javascript在JSF模板下不起作用

haj*_*ime 5 html javascript jsf facelets jsf-2

我正在使用JSF模板和Primefaces.

Javascript代码似乎不适用于ui:composition和ui:define标签.以下代码未命中loaded()方法.这是content.xhtml文件

<h:head>
<script language="javascript">
    function loaded() {
        alert("Working!!");
    }
</script>
</h:head>

<ui:composition template="/template/template.xhtml">
<ui:define name="content">
<h:body style="width:100%;height:100%;" onload="loaded()">
     <p class="item">Random text</p>
</h:body>
</ui:define>
</ui:composition>
Run Code Online (Sandbox Code Playgroud)

但是当我删除define和composition标签时,会调用加载的函数.知道为什么会这样吗?

这是模板文件

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">


<h:head>
<title><ui:insert name="title">Template</ui:insert></title>
</h:head>

<h:body>

<div id="header">
    <ui:insert name="header">
        <ui:include src="../menu.xhtml" />
    </ui:insert>
</div>


<div id="content">
    <ui:insert name="content">
        <ui:include src="../content.xhtml" />
    </ui:insert>
</div>

<div id="footer">
    <ui:insert name="footer">
        This is a footer
    </ui:insert>
</div>
Run Code Online (Sandbox Code Playgroud)

Bal*_*usC 13

一切 <ui:composition>忽略构建视图中.此外,<h:body>再次重新声明是不必要的.要使用在页面加载期间运行的脚本,最好使用a <h:outputScript target="body">.这将被重新定位到body的末尾,因此在构建必要的HTML DOM元素之后调用它.这也比一个快一点onload.

总而言之,您的整体 content.xhtml必须如下所示:

<ui:composition template="/template/template.xhtml"
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:ui="http://java.sun.com/jsf/facelets"
>
    <ui:define name="content">
        <h:outputScript target="body">
            alert("Working!!");
        </h:outputScript>

        <p class="item">Random text</p>
    </ui:define>
</ui:composition>
Run Code Online (Sandbox Code Playgroud)

也可以看看: