我有一个网页,使用ajax / json和把手更新其内容。现在我想对我的日期字段使用bootstrap-datepicker,但在用把手更新DOM之后,javascript事件不起作用。
我的javascript
$(function(){
var refresher = function () {
$.getJSON( "{% url 'characters:journal_json' 1 %}", function(obj) {
refresh_timer = obj.refresh_timer * 1000;
setTimeout(refresher, refresh_timer);
if (obj.content) {
// do shit with content and data
var source = $("#JournalTemplate").html();
var template = Handlebars.compile(source);
var html = template(obj.content);
$("#JournalContent").replaceWith(html);
}
});
};
setTimeout(refresher, 300); // 0.3 seconds
});
$('.datepicker').datepicker({
format: "mm-dd-yyyy",
autoclose: true
});
Handlebars模板(解决此问题后将展开):
<form class="form-inline" action="" method="GET" id="FilterForm">
<input class="form-control input-sm datepicker" id="id_end_date" name="end_date" type="text" value="05-26-2015" />
<button type="submit" class="btn btn-primary btn-sm">Filter</button>
</form>
答案 0 :(得分:0)
尝试这种方式:
$('body').on('focus', '.datepicker', function () {
$(this).datepicker({
format: "mm-dd-yyyy",
autoclose: true
});
});
使用on
时,也会为动态元素触发事件
答案 1 :(得分:0)
首先,bootstrap使用jQuery,所以请确认你在bootstrap.js之前放了jQuery脚本。之后在标记内部编写自己的脚本,然后在JavaScript中调用自执行/匿名函数,称为IIFE(立即调用函数表达式)。所以,这是一个总是编写脚本的好方法。请尝试如下。
(function(){
----- Your Code ----
})();
绝对你会摆脱所有这些。谢谢。
答案 2 :(得分:0)
我做了一招,请试试这个,
$(function(){
var refresher = function () {
$.getJSON( "{% url 'characters:journal_json' 1 %}", function(obj) {
refresh_timer = obj.refresh_timer * 1000;
setTimeout(refresher, refresh_timer);
if (obj.content) {
// do shit with content and data
var source = $("#JournalTemplate").html();
var template = Handlebars.compile(source);
var html = template(obj.content);
$("#JournalContent").replaceWith(html);
bindDatepicker(); // *** Here I am binding again...
}
});
};
setTimeout(refresher, 300); // 0.3 seconds
});
function bindDatepicker() {
$('.datepicker').datepicker({
format: "mm-dd-yyyy",
autoclose: true
});
}
每次更新HTML时,此代码都会绑定datepicker
。
希望它有所帮助。