jQuery - 比较字符串日期然后在Repeater中添加类(C#.net webform)

时间:2016-04-07 21:30:25

标签: c# jquery asp.net

我有以下布局:

<asp:Repeater ID="rpDB_item" runat="server" OnItemDataBound="rpDB_item_ItemDataBound">
   <ItemTemplate>
      <div class="row">
          <div>...</div>
          <div>...</div>
          <div class="anj col-md-2 col-xs-2" id="bkdate" runat="server"><%# Eval("myDate") %> </div> 
          <div>...</div>
          <div>...</div>
          <div>...</div>                                                  
      </div> 
   </ItemTemplate>
</asp:Repeater>

我想要做的是$(document).ready检查bkdate(字符串)的所有实例,看看它是否比今天的日期少.addClass().removeClass()取决于真/假。我想我只是不完全理解jQuery但可以使用一些帮助。我在$(document).ready(Function(){...

中有以下内容
var date2 = Date.now('MM/dd/yyyy');
if ($('id*=bkdate]').val() < date2) {
        $(this).addClass("green");
  } else {
        $(this).addClass("red");
  };

我认为问题在于(this)没有引用任何内容。我做错了什么,哪种方法更好?

2 个答案:

答案 0 :(得分:1)

您可以在后面的代码中执行此操作,使用itemDatabound事件,然后您可以在那里执行您想要的操作:

 void R1_ItemDataBound(Object Sender, RepeaterItemEventArgs e) {

      // This event is raised for the header, the footer, separators, and items.

      // Execute the following logic for Items and Alternating Items.
      if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) {

         if (((Evaluation)e.Item.DataItem).Rating == "Good") {
            ((Label)e.Item.FindControl("RatingLabel")).Text= "<b>***Good***</b>";
         }
      }
   }    

您可以在此处找到更多信息:https://msdn.microsoft.com/es-es/library/system.web.ui.webcontrols.repeater.itemdatabound%28v=vs.110%29.aspx,e是正在处理的项目。

用于从codebehind设置css类:

 if(Object<DateTime.now)
 Object.Attributes.Add("class", "some-class")
else
 Object.Attributes.Add("class", "some-class")

答案 1 :(得分:0)

刚刚找到我的问题。我将数据结果更改为DateTime。它隐式转换为字符串并导致整个错误 这是_ItemDataBound事件中的代码:

    ...
    HtmlGenericControl dtbackup = ((HtmlGenericControl)e.Item.FindControl("bkdate"));
DateTime date2 = DateTime.Today;
            DateTime idate = (DateTime)(DataBinder.Eval(e.Item.DataItem, "myDate"));
if (idate < date2)
            {
                dtbackup.Attributes.Add("class", "bad");
            }
            else
            {
                dtbackup.Attributes.Add("class", "good");
            }

感谢您的帮助