我有我的jQuery UI日期選取器的問題。我有這樣的代碼:爲什麼我的jQuery腳本只執行一次?
<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鏈接,但只有一次。當我更改日期時,腳本不會執行。
這是因爲你正在尋找一個靜態值:'url = url.replace('05&',day +'&');',當你第一次改變日期到一天!= 5'replace'函數將會沒有找到替換的東西 – empiric