为什么我的 jQuery 脚本只执行一次?

Why my jQuery script executes just once?

我的 jQuery UI 日期选择器有问题。我有这个代码:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.12.1/jquery-ui.min.js" integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU=" crossorigin="anonymous"></script>
<script>
  jQuery(document).ready(function($) {
    $('#datepickerFrom').datepicker({
      dateFormat: 'yy-m-d',
      inline: true,
      onSelect: function(dateText, inst) {
        var date = $(this).datepicker('getDate'),
          day = date.getDate(),
          month = date.getMonth() + 1,
          year = date.getFullYear();

        var url = $('#reservation').attr('href');
        url = url.replace('05&', day + '&');
        $('#reservation').attr('href', url);

        var url2 = $('#reservation').attr('href');
        url2 = url2.replace('12', month);
        $('#reservation').attr('href', url2);

        var url3 = $('#reservation').attr('href');
        url3 = url3.replace('2016', year);
        $('#reservation').attr('href', url3);
      }
    });

    $('#datepickerTo').datepicker({
      dateFormat: 'yy-m-d',
      inline: true,
      onSelect: function(dateText, inst) {
        var date = $(this).datepicker('getDate'),
          day = date.getDate(),
          month = date.getMonth() + 1,
          year = date.getFullYear();

        var url4 = $('#reservation').attr('href');
        url4 = url4.replace('=2016', '=' + year);
        $('#reservation').attr('href', url4);

        var url5 = $('#reservation').attr('href');
        url5 = url5.replace('13', +month);
        $('#reservation').attr('href', url5);

        var url6 = $('#reservation').attr('href');
        url6 = url6.replace('09', day);
        $('#reservation').attr('href', url6);

      }
    });
  });
</script>
<p>Date arrivée :
  <input type="text" id="datepickerFrom">
</p>
<p>Date départ :
  <input type="text" id="datepickerTo">
</p>

<a id="reservation" class="et_pb_button  et_pb_button_0 et_pb_module et_pb_bg_layout_light" href="https://mywebsite.com/book?shs&chkin=2016-12-05&chkout=2016-13-09&step=1">Réservez</a>

当我点击一个日期(datepickerTo 和 datepickerFrom)时,它会更新我的 href link 但只有一次。当我更改日期时,脚本没有执行。

仅在第一次工作,因为您搜索初始值并替换它们。检查你的代码:

var url = $('#reservation').attr('href');
url = url.replace('05&', day + '&');
$('#reservation').attr('href', url);
var url2 = $('#reservation').attr('href');
url2 = url2.replace('12', month);
$('#reservation').attr('href', url2);
var url3 = $('#reservation').attr('href');
url3 = url3.replace('2016', year);
$('#reservation').attr('href', url3);

它基本上取代了给定日期的“05”,给定月份的“12”和给定年份的“2016”。当用户选择不同的日期时,此代码找不到可替换为新日期的任何内容。