我想弄清楚为什么我的函数在更改html代码后停止工作。如何在html更改后调用jquery函数
我有一个div:
<div class="float">
<div class="box" data-speed="3" data-direction="X"><h1>Hola</h1></div>
<div class="box" data-speed="2" data-direction="X"><h1>chau</h1></div>
</div>
而jQuery代码:
$(function() {
$('.box').moveIt();
});
//move elements in different speeds
$.fn.moveIt = function() {
var win = $(window);
var it = $(this);
var instances = [];
$(this).each(function(){
instances.push(new moveItItem($(this)));
});
$('.parallax').on('scroll', function() {
instances.forEach(function(inst){
var wrap = inst.el.parents('.float');
var scrol = win.scrollTop()-wrap.offset().top;
inst.update(scrol);
});
});
}
var moveItItem = function(el){
this.el = $(el);
this.speed = parseInt(this.el.attr('data-scroll-speed'));
this.direction = this.el.attr('data-direction');
};
moveItItem.prototype.update = function(scrollTop){
var pos = scrollTop/this.speed;
this.el.css('transform', 'translate'+this.direction+'(' + -pos + 'px)');
};
确定,直到这里的一切工作,当我滚动元件.box
相应的翻译。
但现在我想修改.float
类的HTML Ajax调用后
//after ajax
$.ajax({
url: 'do_content.php'
}).done(function(result) {
//result = <div class="box" data-speed="3" data-direction="X"><h1>Como estas?</h1></div>
$('.float').html(result);
});
当我解雇再次滚动功能后出现看坏了,我得到这个消息:
Uncaught TypeError: Cannot read property 'top' of undefined
at http://localhost/ophelia/public/js/control.js?v=1487219951:197:45
at Array.forEach (native)
at HTMLDivElement.<anonymous> (http://localhost/ophelia/public/js/control.js?v=1487219951:195:13)
at HTMLDivElement.dispatch (http://localhost/ophelia/public/utilities/jquery/jquery-3.1.1.min.js:3:10315)
at HTMLDivElement.q.handle (http://localhost/ophelia/public/utilities/jquery/jquery-3.1.1.min.js:3:8342)
据我所知,只有当我改变类.box
(我试图改变唯一的h1
,它并没有中断,但我想改变一切以改变速度)的元素,才会出现此消息
如何重新启动该功能?
我试图用$('.box').moveIt();
再次调用它,但仍得到相同的错误
我知道是一个长期的问题,但没有找到另一种方式来解释我的问题
你能后的代码为您的AJAX功能为好,好吗? – thesublimeobject
编辑我的朋友 –
当您尝试重新调用该函数时,是否将该调用放在'done()'方法内部,还是在整个ajax方法之后? – thesublimeobject