切断JavaScript分割函数传递的最后几个值的字符

问题描述 投票:0回答:1

我有Javascript代码传递上一页的开始和结束时间值,但是,起始值包含不需要的其他字符。有没有办法可以减少不必要的角色?

转发时搜索栏中的URL为localhost:56363/Bookings.aspx#start=27/02/2018 12:30&end=27/02/2018 17:30&end将传递到开始输入框但不需要。 JavaScript代码如下:

<script type="text/javascript">
  $(document).ready(function () {
    hash();
    function hash() {
      var hashParams = window.location.hash.substr(1).split('#');
      for (var i = 0; i < hashParams.length; i++) {
        var p = hashParams[i].split('=');
        document.getElementById("<%=start.ClientID%>").value = decodeURIComponent(p[1]);
      }
      var hashParams = window.location.hash.substr(1).split('&');
      for (var i = 0; i < hashParams.length; i++) {
        var p = hashParams[i].split('=');
        document.getElementById("<%=end.ClientID%>").value = decodeURIComponent(p[1]);;
      }
    }
  });
 </script>
javascript asp.net split webforms
1个回答
0
投票

哈希参数?!什么!

大多数应用程序将使用查询参数和一个看起来像localhost:56363/Bookings.aspx?start=27/02/2018 12:30&end=27/02/2018 17:30的网址注意?而不是哈希。查询参数将以window.location.search的形式提供

无论如何。将您的hash()功能更改为

function hash(){
    var hash = window.location.hash;

    var start = hash.match(/start=([^&]+)/)[1];
    document.getElementById("<%=start.ClientID%>").value = decodeURIComponent(start);

    var end = hash.match(/end=([^&]+)/)[1];
    document.getElementById("<%=end.ClientID%>").value = decodeURIComponent(end);
}

正则表达式将找到相关参数,捕获组([^&]+)将捕获每个参数的值。然后我们使用[1]来检索每个参数的值。

© www.soinside.com 2019 - 2024. All rights reserved.