Javascript无法通过调用其ID来访问JSF组件 [英] Javascript fails to access a JSF component by calling through its id

查看:61
本文介绍了Javascript无法通过调用其ID来访问JSF组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试以下代码段,以通过引用其ID来访问Javascript中的JSF组件.但这失败了.

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组件:

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

JavaScript代码:

Javascript code:

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

第一个警报可以通过解析元素的正确ID来证明JS函数被称为&已传递正确的ID,但无法显示第二个警报.仅当将JSF组件的ID传递给此JavaScript函数但与非JSF组件一起正常工作时,才会发生这种情况.

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.

如何使其正常工作?

推荐答案

JSF在父级

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" />
    ...

最终将以生成的HTML格式

will end up in generated HTML as

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

(右键单击Web浏览器中的页面,然后选择查看源代码"以自己查看)

:在CSS标识符中是非法的.选择它是为了使最终用户不会在组件ID中意外使用它,这只会导致JSF端的参数和组件无法访问.要使用jQuery中的CSS选择器选择ID为:的元素,您需要通过反斜杠对其进行转义或使用[id=...]属性选择器.

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 + '"]');

或者,从JSF 2.0开始,您可以用web.xml中的javax.faces.SEPARATOR_CHAR上下文参数覆盖ID分隔符,并使用其他但CSS有效的值,例如-.但是,您需要注意不要在任何JSF组件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.

作为另一种完全不同的选择,您也可以只传递整个HTML DOM元素本身.

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

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

以便您可以

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

无需摆弄ID.

这篇关于Javascript无法通过调用其ID来访问JSF组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆