2012-04-28 69 views
2

我想將不同的樣式應用於列表中的第一個元素。VisualForce - 有條件的html標籤

我目前正在嘗試使用一個計數器來用class應用li只有當cnt==0但我不能包括在OutputText標籤<>支架。有什麼方法可以使用條件來跳過括號或將class插入到<li>標記中嗎?

我知道這可以在使用JavaScript之後完成,但我寧願避免它。

<apex:variable var="cnt" value="{!0}" /> 
<apex:repeat value="{!items}" var="item" > 
    <!-- only render the class if it is the first element --> 
    <apex:OutputText value="<li class="activeLI">" rendered="{!cnt==0}" /> 
    <apex:OutputText value="<li>" rendered="{!cnt!=0}" />   

     <img src="{!$Resource[item.Image__c]}" width="85" height="90"/> 
    </li> 
    <apex:variable var="cnt" value="{!cnt+1}"/> 
</apex:repeat> 

回答

4

Visualforce是嚴格的,每個元素必須有開始和結束標籤或必須自閉合。在編譯時,Visualforce會抱怨,因爲它只能看到收「禮」的標籤,而不是有條件開放「禮」的標籤,一種解決方案是使類名稱的變量如下:

<apex:variable var="cnt" value="{!0}" /> 
<apex:variable var="class" value=""/> 
<apex:repeat value="{!items}" var="item" > 
    <apex:variable var="class" value="activeLI" rendered="{!cnt==0}"/> 
    <apex:variable var="class" value="" rendered="{!cnt!=0}"/> 
    <li class="{!class}"> 
     ... 
    </li> 
    <apex:variable var="cnt" value="{!cnt+1}"/> 
</apex:repeat> 
+0

好主意!我通過全部刪除計數器進行了一些小修改,在定義時將'class'設置爲'activeLI',然後在第一次使用後清空該值。非常感謝這個想法。 – UserIsStuck 2012-04-30 00:44:16

+0

謝謝,還有不錯的改進! – manubkk 2012-04-30 04:48:51

0

您是否考慮過使用<apex:dataList>?我認爲它可能會完成你想要做的事情。

1

你有沒有考慮使用CSS選擇器?以下是如何設置列表的第一個元素的示例。

<style> 
ul.myList > li:first-child {color : red} 
</style> 

<ul class="myList"> 
    <li>this is red</li> 
    <li>this has default formatting</li> 
</ul>