1
我正在批量處理一些對象並生成一些標記以供它們在輪播中使用。HtmlTextWriter將類添加到已具有一個元素的元素
當我在批處理中的最後一個項目時,我想給該項目一個類,以便我可以相應地設計它。
我能夠給項目一個內聯樣式來獲得它,但我想如果我嘗試添加一個類到元素(它已經被給予一個類)它不會顯示在標記中。非常奇怪 - 你能不能給一個元素分配多個類,它是不是將類追加到現有類中?
這是我的工作代碼,希望有人能提醒:
public static string CreateCarouselMarkup(BrandCollection carouselBrands)
{
StringWriter stringWriter = new StringWriter();
using (HtmlTextWriter textWriter = new HtmlTextWriter(stringWriter))
{
//List items
textWriter.RenderBeginTag(HtmlTextWriterTag.Li);
int idx = 0;
foreach (Brand brand in carouselBrands)
{
idx++;
textWriter.AddAttribute(HtmlTextWriterAttribute.Href, string.Format("/brands/{0}/", brand.SeoInfo.SeoUrl));
textWriter.RenderBeginTag(HtmlTextWriterTag.A);
textWriter.AddAttribute(HtmlTextWriterAttribute.Class, "carousel-image");
textWriter.AddAttribute(HtmlTextWriterAttribute.Src, brand.Logo);
textWriter.AddAttribute(HtmlTextWriterAttribute.Alt, brand.Title);
//If we are on the last item or last item for this batch
if (idx == carouselBrands.Count())
{
textWriter.AddAttribute(HtmlTextWriterAttribute.Class, "last-img");
}
textWriter.RenderBeginTag(HtmlTextWriterTag.Img);
textWriter.RenderEndTag();//End Img tag
textWriter.RenderEndTag();//End A tag
}
textWriter.RenderEndTag();//End Li tag
}
return stringWriter.ToString();
}
這裏是標記的小樣本被渲染:
<ul class="bjqs" style="height: 80px; width: 100%; display: block;">
<li class="bjqs-slide" style="height: 80px; width: 100%; display: list-item;">
<a href="/brands/kaldewei/">
<img class="carousel-image" src="/Images/Brands/Logos/kaldewei_logo_02.png" alt="Kaldewei">
</a>
<a href="/brands/iotti/">
<img class="carousel-image" src="/Images/Brands/Logos/Iotti-logo.jpg" alt="Iotti">
</a>
<a href="/brands/ellis/">
<img class="carousel-image" src="/Images/Brands/Logos/Ellis-logo.jpg" alt="Ellis">
</a>
<a href="/brands/burgbad/">
<img class="carousel-image" src="/Images/Brands/Logos/Burgbad-logo.png" alt="Burgbad">
</a>
</li>
<li class="bjqs-slide" style="height: 80px; width: 100%; display: none;">
<a href="/brands/pura/">
<img class="carousel-image" src="/Images/Brands/Logos/Pura-logo.png" alt="Pura">
</a>
</li>
</ul>
我期待的類last-img
要應用到每個批次中的最後一個圖像(我不想爲此使用CSS3屬性)。在上面的例子中,它將應用於burgbad
和pura
。
查看網頁源顯示呈現類也兩次,我猜鉻(檢查元素)被檢測的重複屬性併爲我刪除它。當然,正確的行爲是將它追加到任何現有的類中,但這是多麼奇怪。好吧,你的解決方案將會好起來,謝謝! – DGibbs
@DGibbs Yup,我相信Chrome中的「檢查元素」會給你提供一切的「解釋結果」。你甚至會發現你的腳本在「源代碼」中生成了標記 - 實際上非常酷,儘管它可能會讓你失望:) – EdSF