将javascript值附加到gridview超链接。你知道为什么我的代码没有';不行?

将javascript值附加到gridview超链接。你知道为什么我的代码没有';不行?,javascript,jquery,asp.net,gridview,Javascript,Jquery,Asp.net,Gridview,我们有一个javascript,它获取开始日期和结束日期,计算它们之间的差异,并将值存储在一个名为hourDiff的变量中 下面是js的相关部分 为了避免作用域问题,在javascript的顶部定义了一个名为hourDiff的gobal变量,该变量位于任何函数的外部“ 其思想是最终将hourDiff附加到下面的gridview超链接控件,并将名称-值对作为querystring传递给另一个名为Reseve.aspx的页面 <asp:HyperLink ID="siteId" class="

我们有一个javascript,它获取开始日期和结束日期,计算它们之间的差异,并将值存储在一个名为hourDiff的变量中

下面是js的相关部分

为了避免作用域问题,在javascript的顶部定义了一个名为hourDiff的gobal变量,该变量位于任何函数的外部“

其思想是最终将hourDiff附加到下面的gridview超链接控件,并将名称-值对作为querystring传递给另一个名为Reseve.aspx的页面

<asp:HyperLink ID="siteId" class="js_siteid" style="color:#111" runat="server" navigateurl='<%# String.Format("Reserve.aspx?id={0}&groupsize={1}&facilityFees={2}&extrahour={3}&depoitAmt={4}&cancelAmt={5}&keydeptAmt={6}", Eval("siteId"), Eval("capacity"),Eval("RentalFeeAmount"),Eval("ExtraHourAmount"),Eval("DepositAmount"),Eval("CancellationAmount"),Eval("KeyDepositAmount")) %>' Text='Select' />

因为在点击搜索按钮之后,超链接才暴露于javascript中,所以我在下面有另一个javascript,用于向超链接添加小时并传递到另一个页面

此javascript位于html页面的底部:

<script type="text/javascript">
var links = document.getElementsByClassName("js_siteid");
if ( links.length > 0 )
{
    links[0].onclick = function() {
        this.href += ( "&hoursdiff=" + hourDiff );
        return true;
    }
}
</script>
</body>
</html>


  <script type="text/javascript">
                 **var hourDiff = 0;**
                $(window).load(function () {
                    $("#txtFromDate").datepicker();
                    $('#timeStart').timepicker({ showPeriod: true,
                        onHourShow: OnHourShowCallback,
                        onMinuteShow: OnMinuteShowCallback
                    });

                    $("#txtToDate").datepicker();
                    $('#timeEnd').timepicker({ showPeriod: true,
                        onHourShow: OnHourShowCallback,
                        onMinuteShow: OnMinuteShowCallback
                    });
                    function OnHourShowCallback(hour) {
                        if ((hour > 20) || (hour < 6)) {
                            return false; // not valid
                        }
                        return true; // valid
                    }
                    function OnMinuteShowCallback(hour, minute) {
                        if ((hour == 20) && (minute >= 30)) { return false; } // not valid
                        if ((hour == 6) && (minute < 30)) { return false; }   // not valid
                        return true;  // valid
                    }
                    $('#btnSearch').on('click', function () {
                        var sDate = $("#txtFromDate").val();
                        var sTime = $("#timeStart").val();

                        var eDate = $("#txtToDate").val();
                        var eTime = $("#timeEnd").val();

                        var startDate = new Date(sDate + " " + sTime).getHours();
                        var endDate = new Date(eDate + " " + eTime).getHours();

                        //Calulate the time difference
                         **hourDiff = endDate - startDate;**
                        //alert(hourDiff);

                        //Check if hour difference is less than 4 hours and show the message accordingly
                        if (hourDiff < 4) {
                            var r = false; $($("<div>A mininum of 4 hours is required!</div>")).dialog({ closeOnEscape: false, resizable: false, modal: true, open: function (event, ui) { $(".ui-dialog-titlebar-close").hide(); }, buttons: { Close: function () { r = false; $(this).dialog("close"); } }, close: function () { return r; } });
                            return false;
                        }

                        //Add the check condition if the user is above the 4 hours time frame
                        if (hourDiff > 4) {
                            var r = confirm("There may be additional fees for going over the 4 hours!");
                            if (r == true) { // pressed OK
                                return true;
                            } else { // pressed Cancel
                                return false;
                            }
                        }
                    });
                });
        </script>

var links=document.getElementsByClassName(“js_siteid”);
如果(links.length>0)
{
链接[0]。onclick=function(){
this.href+=(“&hoursdiff=“+hourDiff”);
返回true;
}
}
**var hourDiff=0**
$(窗口)。加载(函数(){
$(“#txtFromDate”).datepicker();
$('#timeStart')。时间选择器({showPeriod:true,
onHourShow:onHourShow回调,
onMinuteShow:OnMinuteShowCallback
});
$(“#txtToDate”).datepicker();
$('#timeEnd')。时间选择器({showPeriod:true,
onHourShow:onHourShow回调,
onMinuteShow:OnMinuteShowCallback
});
函数OnHourShowCallback(小时){
如果((小时>20)| |(小时<6)){
返回false;//无效
}
返回true;//有效
}
函数OnMinuteShowCallback(小时,分钟){
如果((小时==20)和(&(分钟>=30)){return false;}//无效
如果((小时==6)和(&(分钟<30)){return false;}//无效
返回true;//有效
}
$('#btnSearch')。在('click',函数(){
var sDate=$(“#txtFromDate”).val();
var sTime=$(“#timeStart”).val();
var-eDate=$(“#txtToDate”).val();
变量eTime=$(“#timeEnd”).val();
var startDate=新日期(sDate+“”+sTime).getHours();
var endDate=新日期(eDate+“”+eTime).getHours();
//计算时差
**hourDiff=结束日期-开始日期**
//警报(hourDiff);
//检查时差是否小于4小时,并相应显示消息
如果(小时数<4){
var r=false;$($(需要最少4小时!)).dialog({closeOnEscape:false,可调整大小:false,model:true,open:function(event,ui){$(.ui dialog titlebar close”).hide();},按钮:{close:function(){r=false;$(this.dialog(“close”);},close:function(){return r;});
返回false;
}
//如果用户超过4小时的时间范围,则添加检查条件
如果(小时数>4){
var r=确认(“超过4小时可能会有额外费用!”);
如果(r==true){//按下OK
返回true;
}否则{//按取消
返回false;
}
}
});
});
每次我编译代码并点击Select链接时,hourDiff总是显示0的值,而不是开始日期和结束日期之间的差值

你知道我做错了什么吗

Protected Sub ValidateDuration(ByVal sender As Object, ByVal args As ServerValidateEventArgs)
  Dim validator As Control = DirectCast(sender, Control)
  Dim row As Control = validator.NamingContainer

  Dim startHour As Integer = Integer.Parse(DirectCast(row.FindControl("startHour"), DropDownList).SelectedValue)
  Dim startMinutes As Integer = Integer.Parse(DirectCast(row.FindControl("startMinutes"), DropDownList).SelectedValue)
  Dim startAmPm As String = DirectCast(row.FindControl("startAmPm"), DropDownList).SelectedValue

  Select Case startAmPm
    Case "AM"
        If startHour = 12 Then
            startHour = 0
        End If

    Case "PM"
        If startHour <> 12 Then
            startHour += 12
        End If

    Case Else
        args.IsValid = True
        Return
  End Select

  Dim endHour As Integer = Integer.Parse(DirectCast(row.FindControl("endHour"), DropDownList).SelectedValue)
  Dim endMinutes As Integer = Integer.Parse(DirectCast(row.FindControl("endMinutes"), DropDownList).SelectedValue)
  Dim endAmPm As String = DirectCast(row.FindControl("endAmPm"), DropDownList).SelectedValue

  Select Case endAmPm
    Case "AM"
        If endHour = 12 Then
            endHour = 0
        End If

    Case "PM"
        If endHour <> 12 Then
            endHour += 12
        End If

    Case Else
        args.IsValid = True
        Return
  End Select

  Dim hoursDiff As Integer = endHour - startHour
  If endMinutes < startMinutes Then
    hoursDiff -= 1
  End If

  args.IsValid = hoursDiff >= 2
受保护的子验证(ByVal发送方作为对象,ByVal args作为服务器ValidateEventargs)
Dim验证程序作为控件=DirectCast(发送方,控件)
Dim行作为控件=validator.NamingContainer
Dim startHour As Integer=Integer.Parse(DirectCast(row.FindControl(“startHour”),DropDownList).SelectedValue)
Dim startMinutes As Integer=Integer.Parse(DirectCast(row.FindControl(“startMinutes”),DropDownList.SelectedValue)
Dim startAmPm As String=DirectCast(row.FindControl(“startAmPm”),DropDownList)。SelectedValue
选择案例startAmPm
案例“AM”
如果startHour=12,则
startHour=0
如果结束
案件“PM”
如果你是12号星的话
星空+=12
如果结束
其他情况
args.IsValid=True
返回
结束选择
Dim endHour As Integer=Integer.Parse(DirectCast(row.FindControl(“endHour”),DropDownList).SelectedValue)
Dim endMinutes As Integer=Integer.Parse(DirectCast(row.FindControl(“endMinutes”),DropDownList.SelectedValue)
Dim endAmPm As String=DirectCast(row.FindControl(“endAmPm”),DropDownList)。SelectedValue
选择Case endAmPm
案例“AM”
如果endHour=12,则
endHour=0
如果结束
案件“PM”
如果第12小时结束,那么
结束时间+=12
如果结束
其他情况
args.IsValid=True
返回
结束选择
Dim hoursDiff为整数=结束小时-开始小时
如果endMinutes=2

End Sub

更新2015-02-27~13:40美国东部夏令时:将hiddenfield附加到超级链接服务器端

我正在使用gridview 1,因为我不知道您的gridview的名称。 在
gridview 1
RowDatabound
事件中(注意添加了“&hourDiff
Protected Sub ValidateDuration(ByVal sender As Object, ByVal args As ServerValidateEventArgs)
  Dim validator As Control = DirectCast(sender, Control)
  Dim row As Control = validator.NamingContainer

  Dim startHour As Integer = Integer.Parse(DirectCast(row.FindControl("startHour"), DropDownList).SelectedValue)
  Dim startMinutes As Integer = Integer.Parse(DirectCast(row.FindControl("startMinutes"), DropDownList).SelectedValue)
  Dim startAmPm As String = DirectCast(row.FindControl("startAmPm"), DropDownList).SelectedValue

  Select Case startAmPm
    Case "AM"
        If startHour = 12 Then
            startHour = 0
        End If

    Case "PM"
        If startHour <> 12 Then
            startHour += 12
        End If

    Case Else
        args.IsValid = True
        Return
  End Select

  Dim endHour As Integer = Integer.Parse(DirectCast(row.FindControl("endHour"), DropDownList).SelectedValue)
  Dim endMinutes As Integer = Integer.Parse(DirectCast(row.FindControl("endMinutes"), DropDownList).SelectedValue)
  Dim endAmPm As String = DirectCast(row.FindControl("endAmPm"), DropDownList).SelectedValue

  Select Case endAmPm
    Case "AM"
        If endHour = 12 Then
            endHour = 0
        End If

    Case "PM"
        If endHour <> 12 Then
            endHour += 12
        End If

    Case Else
        args.IsValid = True
        Return
  End Select

  Dim hoursDiff As Integer = endHour - startHour
  If endMinutes < startMinutes Then
    hoursDiff -= 1
  End If

  args.IsValid = hoursDiff >= 2
Protected Sub GridView1_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
  If e.Row.RowType = DataControlRowType.DataRow Then
    dim hl as HyperLink = if(e.Row.FindControl("siteId"), Nothing)
    If hl IsNot Nothing then
      hl.NavigateURL = String.Format("Reserve.aspx?id={0}&groupsize={1}" & _
          "&facilityFees={2}&extrahour={3}&depoitAmt={4}&cancelAmt={5}" & _
          "&keydeptAmt={6}&hourDiff={7}",
          DataBinder.Eval("siteId"),
          DataBinder.Eval("capacity"),
          DataBinder.Eval("RentalFeeAmount"),
          DataBinder.Eval("ExtraHourAmount"),
          DataBinder.Eval("DepositAmount"),
          DataBinder.Eval("CancellationAmount"),
          DataBinder.Eval("KeyDepositAmount"),
          hf1.Value )
    End If
  End If
End Sub
' At class level define the variable:
Dim hourDiff as DateTime = nothing

' In the gridview databinding event do your calculation
Private Sub GridView1_DataBinding(sender As Object, e As System.EventArgs) Handles GridView1.DataBinding
  Dim S as New DateTime( <replace with relevant parameters> )
  Dim E as New DateTime( <replace with relevant parameters> )

  hourDiff = DataDiff(DateInterval.Hour, S, E)
End Sub

' Then in the row databound event append the difference to the hyperlink
Private Sub GridView1_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
  If e.Row.RowType = DataControlRowType.DataRow Then
    dim hl as HyperLink = if(e.Row.FindControl("siteId"), Nothing)
    If hl IsNot Nothing then
      hl.NavigateURL = <build your Hyperlink and Append hourDiff>
    End If
  End If
End Sub
<asp:HiddenField ID="hf1" runat="server" ClientIDMode="Static">
// define hourDiff
var hourDiff; 

// Using jquery place an object reference to the hidden field into hourDiff
hourDiff = $("#hf1");  

// Do your time calculations and assign results to hourDiff
hourDiff.val( time_calc_results );  

// The above places the results in the hidden field Value property
// which will be available in the code behind as as `hf1.Value` after postback
// Assuming hourDiff is defined as 
var hourDiff = $('#hf1');

... (other stuff)

// and you calc and assign to hourDiff as this:
hourDiff.val( endDate - startDate);

... (maybe more other stuff)

// then you modify your hyperlinks like this
$( "#GridView1 a.js_siteid" ).each( function( i, e ) {
    this.href += "&diff=" + hourDiff.val();
} );