简体   繁体   English

stellar.js无法通过AJAX处理动态加载的元素

[英]stellar.js not working with dynamically loaded elements via AJAX

I'm using the fantastic Stellar.js ( http://markdalgleish.com/projects/stellar.js/ ) for parallax on a recent project, but I've run into a challenge: 我在最近的项目中使用了奇妙的Stellar.js( http://markdalgleish.com/projects/stellar.js/ )进行视差,但是我遇到了一个挑战:

Stellar isn't noticing when I change content via AJAX (in this case loading in new div's from an html file and using jQuery's replaceWith method). 当我通过AJAX更改内容时,Stellar没有注意到(在这种情况下,是从html文件加载新的div并使用jQuery的replaceWith方法)。 So, my new elements have no parallax, even though they have stellar data attributes. 因此,即使我的新元素具有恒星数据属性,也没有视差。

I've tried calling the .stellar function on my window again after the AJAX is complete, but it doesn't do anything. 我已经尝试在AJAX完成后在窗口上再次调用.stellar函数,但是它没有任何作用。

How can I get Stellar to correctly apply parallax to the new AJAX'd in elements? 如何获得Stellar正确将视差应用于元素中的新AJAX?

I know this question was posted a long time ago has been accepted, but for me the solution above did not work, so I just wanted to share this which worked for me. 我知道这个问题发布很久以前就已经被接受了,但是对我来说,以上解决方案不起作用,所以我只想分享对我有用的问题。

After you AJAX call has been successful you can call Stellar's refresh function like so: AJAX调用成功后,您可以像下面这样调用Stellar的刷新功能:

$.stellar('refresh');

Here is the full code: 这是完整的代码:

$.ajax({
    type: 'GET',
    url: ajaxUrl
}).done(function(data) {

    $(targetElement).html(data);

    $.stellar('refresh');

}).fail(function() {

    // Do something else

});

I found that I can run this code in my jQuery AJAX callback and Stellar will then correctly apply parallax to my new AJAX'd in elements: 我发现我可以在jQuery AJAX回调中运行此代码,Stellar随后将视差正确地应用于元素中的新AJAX:

$(window).data('plugin_stellar').destroy();
$(window).data('plugin_stellar').init();

I know that the topic is old but I want to share the solution that I found, hoping that it will be useful for people who are still searching. 我知道这个话题很旧,但是我想分享我找到的解决方案,希望它对仍在搜索的人有用。 First create the function: 首先创建函数:

function init () {
$(window).data('plugin_stellar').refresh();
}

jQuery(document).ready(function () {
// Initialise the plugin when the DOM is ready to be acted upon
init();
});

Second insert this line in your Ajax call: 其次,将此行插入到您的Ajax调用中:

// Reinitialise plugins:
    init(); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM