且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在RichFaces / JSF页面中嵌入和调用javascript脚本

更新时间:2023-12-05 19:25:58

无论您使用何种类型的服务器端标签,当您的页面到达浏览器时,这一切都已消失,而且只是HTML。 (至少,它***是,或者事情无论如何都不会工作。)你需要做的是安排你的代码被加载事件处理程序调用。有多种方法可以做到这一点,但最简单的方法是:

Regardless of what sorts of server-side tags you're using, by the time your page gets to the browser that's all gone and it's just HTML. (At least, it had better be, or things won't work anyway.) What you need to do is arrange for your code to be called by a "load" event handler. There are various ways to do this, but the simplest would be this:

 <f:verbatim>
     <script type="text/javascript">
        window.onload = function() {
            alert("hi");
        }
    </script>
</f:verbatim>

现在,对于初始化页面的另一部分,重要的是HTML中的最终结果。您需要安排某种HTML容器(< div> 或其他东西,具体取决于您的页面设计),您会希望它拥有唯一的id属性。然后,您的Javascript可以使用id来查找元素并设置其内容:

Now as to initializing another part of the page, once again what matters is what ends up in the HTML. You'll want to arrange for there to be some sort of HTML container (a <div> or something, depending on your page design) and you'll want it to have a unique "id" attribute. Your Javascript can then use the "id" to find the element and set its contents:

    var elem = document.getElementById("whatever");
    elem.innerHTML = // ... whatever ;

您可能会在加载功能中执行此操作。

You'd probably do that stuff inside the "load" function.

此外,如果您使用的是Facelets而不是JSP(基于XML的视图技术),如果您的JavaScript包含注释//或文字(例如&lt),则需要添加XML CDATA部分分隔符以下是XML CDATA分隔符的示例:

Also, if you're using Facelets instead of JSP, which is a XML based view technlogy, you will need to add the XML CDATA section delimiters if your JavaScript contains comments // or literals such as <, >, &&, etc. Here's the example with the XML CDATA delimiters:

 <f:verbatim>
     <script type="text/javascript">
     //<![CDATA[
        //Comments won't show error now.
        window.onload = function() {
            alert("hi");
        }
    //]]>
    </script>
</f:verbatim>

您可以看到何时在这里使用CDATA。你如果您正在创建HTML5页面,则不需要这些。

You can see a thorough explanation of when to use CDATA here. You do not need those if you're creating HTML5 pages.

快乐编码!