How to embed and call a javascript script in a RichFaces/JSF page

本小妞迷上赌 提交于 2019-12-04 09:23:42
Pointy

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>

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.

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>

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

Happy coding!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!