问题
I put the date picker in a form in Rails (v4.1.8). And I use eyecon datepicker (disabling dates in the past). http://www.eyecon.ro/bootstrap-datepicker/
<div class="form-group">
<label for="expiration" class="col-sm-2 control-label">
Expiration
</label>
<div class="col-sm-10">
<input type="text" class="span2 form-control" name="expiration" id="dpd1" data-date-format="yyyy-mm-dd">
</div>
</div>
If I was directed to this page, the date picker does not show up when I click the date form. However, if I fresh the page by control+r in chrome. The date picker works well. Alternatively, if I enter the address in the url bar by hand and hit enter, the date picker also works.
It's so strange. Can someone explain it to me?
Another fact may help: If I save the code as html instead of using Rails. It works fine.
Thanks
回答1:
Been there millions of time - it is because of turbolinks. turbolinks gem makes your website much faster - it does not reload the whole page when you click any navigation links, but only those parts of it which are to change (it's huge simplification of what it does, read here for more details)
Naturally your javascript is not tracked by turbolinks and hence it is not executed when new content is loaded, leaving all your elements without any hooks or functionality you would normally have without turbolinks. WHen you refresh the page, the whole page is loaded and all javascript is executed so all works as expected.
I usually deal with it by defining a helper method:
window.onInit = function(handler) {
$(document).on('ready page:change', handler)
}
And then wrap all your javascript which is to run for every page in it:
onInit(function() {
$('#dpd1').datepicker();
}):
来源:https://stackoverflow.com/questions/27866331/date-picker-does-not-show-in-rails-unless-refresh