Javascript fails to access a JSF component by calling through its id

后端 未结 1 1103
时光取名叫无心
时光取名叫无心 2020-12-20 08:04

I am trying out the following piece of code to get access a JSF component in Javascript by referring to its Id. But this fails.

JSF component:



        
相关标签:
1条回答
  • 2020-12-20 09:05

    JSF prepends IDs of parent NamingContainer components (such as <h:form>) in generated client id with : as default separator character. So for example

    <h:form id="foo">
        <p:commandButton id="bar" />
        ...
    

    will end up in generated HTML as

    <form id="foo" name="foo">
        <input type="submit" id="foo:bar" name="foo:bar" />
    

    (rightclick page in webbrowser and choose View Source to see it yourself)

    The : is however illegal in CSS identifiers. This was chosen so that the enduser won't accidently use it in component IDs which would only result in inaccessible parameters and components in the JSF side. To select an element with a : in the ID using CSS selectors in jQuery, you need to either escape it by backslash or to use the [id=...] attribute selector.

    var $element1 = jQuery('#' + id.replace(':', '\\:'));
    // or
    var $element2 = jQuery('[id="' + id + '"]');
    

    Alternatively, since JSF 2.0 you can override the ID separator character by a javax.faces.SEPARATOR_CHAR context parameter in web.xml with a different but CSS-valid value such as -. However, you need to be careful that you don't use this character yourself in any JSF component IDs.

    As a completely different alternative, you can also just pass the whole HTML DOM element itself.

    <p:commandButton onclick="calculatePosition(this)" />
    

    so that you can do

    function calculatePosition(element) {
        var $element = jQuery(element);
        // ...
    }
    

    without fiddling with IDs.

    0 讨论(0)
提交回复
热议问题