我制作了幻灯片。每个幻灯片都有一个放在它顶部的div。 div包含一些文本。我想要做的是,如果h2
和p
元素没有文本,则隐藏包含它们的div。我试图隐藏转发器DataBound事件中的div,但它仍然显示幻灯片上的div。
这是我到目前为止所拥有的:
ASPX:
<asp:Repeater ID="rptSlides" runat="server" ClientIDMode="Static" OnItemDataBound="rptSlides_ItemDataBound">
<ItemTemplate>
<div runat="server" id="slideDiv" class="slide">
<img runat="server" src='<%# Eval("slideImgPath")%>' />
<div id="slideTextdiv" runat="server" class="slideText">
<h2 id="titlePlaceHolder" runat="server" class="slideTitle text-center text-capitalize h2 ">
<%# Eval("slideTitle") %>
</h2>
<p id="textPlaceHolder" runat="server" class="slideDes">
<%# Eval("slideDesc") %>
</p>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
代码背后:
protected void rptSlides_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
foreach (RepeaterItem item in rptSlides.Items)
{
HtmlGenericControl titleText = (HtmlGenericControl)item.FindControl("titlePlaceHolder");
HtmlGenericControl slidetextDesc = (HtmlGenericControl)item.FindControl("textPlaceHolder");
HtmlGenericControl slideDiv = (HtmlGenericControl)item.FindControl("slideTextdiv");
if (titleText.InnerText == "" && slidetextDesc.InnerText == "")
{
slideDiv.Style.Add("Display", "none");
}
}
}
更多信息
我也尝试了以下内容:
foreach (RepeaterItem item in rptSlides.Items)
{
HtmlGenericControl slideDiv = (HtmlGenericControl)FindControlRecursive(item, "slideTextdiv");
HtmlGenericControl titleText = (HtmlGenericControl)FindControlRecursive(item, "titlePlaceHolder");
HtmlGenericControl slidetextDesc = (HtmlGenericControl)FindControlRecursive(item, "textPlaceHolder");
if (string.IsNullOrWhiteSpace(titleText.InnerText) && string.IsNullOrWhiteSpace(slidetextDesc.InnerText))
{
slideDiv.Attributes["class"] = "emptySlideText";
}
}
我在css中创建了一个名为emptySlideText的类,如下所示:
.emptySlideText {
display:none; }
不幸的是,这没有任何效果。
我也尝试过更改行
slideDiv.Style.Add(“显示”,“无”);
到
slideDiv.Attributes.Add(“style”,“display:none”);
但是它再次没有区别
答案 0 :(得分:2)
首先,您的foreach
事件中不需要rptSlides_ItemDataBound
循环,因为转发器控件的ItemDataBound
事件会针对每个项目进行迭代。下一个Div
不是HtmlGenericControl
控件,而是HtmlControl
控件。完成此操作后,您可以使用Visible
属性隐藏div,如下所示: -
protected void rptSlides_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
{
HtmlControl slideTextdiv = (HtmlControl)e.Item.FindControl("slideTextdiv");
HtmlGenericControl titlePlaceHolder = (HtmlGenericControl)e.Item.FindControl("titlePlaceHolder");
HtmlGenericControl textPlaceHolder = (HtmlGenericControl)e.Item.FindControl("textPlaceHolder");
if (titlePlaceHolder != null)
titlePlaceHolder.InnerText = Regex.Replace(titlePlaceHolder.InnerText, @"\r\n?|\n", "").Trim();
if (textPlaceHolder != null)
textPlaceHolder.InnerText = Regex.Replace(textPlaceHolder.InnerText, @"\r\n?|\n", "").Trim();
if (String.IsNullOrEmpty(titlePlaceHolder.InnerText) && String.IsNullOrEmpty(textPlaceHolder.InnerText))
{
slideTextdiv.Visible = false;
}
}
}
请包含using System.Text.RegularExpressions;
以导入Regex
课程。