如何在visualforce页面中为图像标签的id属性赋值?
问题描述:
我不能够动态分配的id值的图像......我指这个图像JavaScript来显示相应向上/向下箭头...这里是代码片段...如何在visualforce页面中为图像标签的id属性赋值?
<apex:variable var="count" value="{!1}"/>
<apex:image id="msn{!count}" url="{!URLFOR($Resource.style_resources, 'images/up-arrow.gif')}" alt="Open-close" />
但我得到编译错误为“字面值预计为id”...
我们不能动态地为id属性赋值吗?
答
你是正确的,你不能动态地分配元素ID。它必须是一个字符串文字。然而,我使用了class属性来创建可以在以后使用的自定义id。我用jQuery来做这件事,它是基于标签类型和类选择元素的功能强大的选择器。
下面的示例只是一个示例,但使用jQuery您可以获得相当的创造性。
<apex:variable var="count" value="{!1}"/>
<apex:image id="msn"
url="{!URLFOR($Resource.style_resources, 'images/up-arrow.gif')}"
alt="Open-close"
styleClass="msn{!count}" />
<apex:includeScript value="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"/>
<script>
jQuery.noConflict();
function doSomethingWithImg() {
try {
var imgElement = jQuery('.msn1');
/*Do what you need to do with the element*/
} catch (e) { /*Ignore Error*/ }
}
</script>
这里是链接到jQuery选择:jQuery Selector Documentation
答
<apex:image id="theImage" value="/img/myimage.gif" width="220" height="55"/>
上面的例子呈现下面的HTML:
<img id="theImage" src="/img/myimage.gif" width="220" height="55"/>
所以改变
<apex:image id="msn{!count}" url="{!URLFOR($Resource.style_resources, 'images/up-arrow.gif')}" alt="Open-close" />
到
<img id="msn{!count}" src="{!URLFOR($Resource.style_resources, 'images/up-arrow.gif')}" alt="Open-close" />