Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

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

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:

<p:commandLink onclick="calculatePosition(this.id)" >
       <h:graphicImage url="2.png"/>
</p:commandLink>

Javascript code:

<script type="text/javascript">
    function calculatePosition(idOfClicked){
        alert(idOfClicked);
        var $element = jQuery('#'+idOfClicked);
        var offset = $element.offset();
        alert(offset.top);
    }
</script>

1st alert works dislaying correct id of the element thereby proving that the JS function is called & correct id has been passed but it fails to display the 2nd alert. This happens only when the id of a JSF component is passed to this JavaScript function but works fine with non JSF components.

How can I make it work correctly ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...