jQuery在动态加载的内容上运行脚本

时间:2018-09-02 15:38:29

标签: javascript jquery dynamic

我使用AJAX请求动态加载页面。在这些页面之一中,我喜欢运行marquee script

由于页面是动态加载的,因此字幕无法使用。

我已经读到我需要将.on用于此类直播活动。我目前有这个:

$(document).on('load', '.marquee', function(event){
    $('.marquee').marquee({
        duration: 25000,
        startVisible: true,
        duplicated: true,
        gap: '5px'
    });
});

如何解决此问题以使选取框正常工作?

1 个答案:

答案 0 :(得分:0)

我认为由于某些晦涩的原因,您无法在Ajax成功回调中初始化选取框...

所以这是一种出路:Mutation Observer

这是一个片段,在其中我改编了MDN示例...并在其中使用setTimeout“模拟” Ajax响应。

// Marquee init function
function MarqueeInit(element){
  element.marquee({
    duration: 25000,
    startVisible: true,
    duplicated: true,
    gap: '5px'
  });
}

// On load, init the static marquee.
MarqueeInit($('.marquee'));


// Simulating an Ajax response
var marqueeString = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut cursus elit magna, non lacinia orci placerat non. Nunc cursus vestibulum orci. Fusce dapibus augue id.";

setTimeout(function(){
  $(".dynamic").append(marqueeString);
},2000);

// Applying a Mutation Observer on the destination div


var targetNode = $(".dynamic")[0];
var config = { attributes: true, childList: true, subtree: true };

var callback = function(mutationsList) {
  for(var mutation of mutationsList) {
    if (mutation.type == 'childList') {
      console.log('A child node has been added or removed.');

      // IMPORTANT!
      // Stop observing NOW because the marquee initialization will start an inifinite loop.
      observer.disconnect();
      
      // Init Marquee!
      MarqueeInit($(".dynamic"));
    }
  }
};

// Create an observer instance
var observer = new MutationObserver(callback);
observer.observe(targetNode, config);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jQuery.Marquee/1.5.0/jquery.marquee.min.js"></script>

<h1>Static marquee</h1>
<div class="marquee">
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis pharetra tellus a sem feugiat, vel blandit ipsum dignissim. Nam tincidunt placerat risus, et pretium ligula tempus id. Nulla tristique, arcu in euismod fringilla, odio erat venenatis arcu, id luctus turpis lorem vel massa. Curabitur at diam eget sem posuere dictum. Sed elementum placerat velit, eget bibendum velit lacinia sed. Nam commodo magna at gravida sodales. Vestibulum at eleifend augue, at condimentum ante.
</div>
<br>
<h1>Dynamic marquee</h1>
<div class="dynamic">
</div>