如何在加载了jQuery Mobile的每个页面上执行相同的javascript函数

时间:2019-02-16 12:20:04

标签: javascript html jquery-mobile

我需要帮助来整理这段代码,目标是加载的每个页面显示3秒钟的阵列图像。

第一页工作正常。问题在于,在第一个页面加载后,每个页面的图像更改速度都会更快。

<div data-role="page" id="page1" class="banners">
 <div data-role="main" class="ui-content">
  <div class="patrocinadores" align="center">
      <img src="" width="100%" class="bannerPatrocinador">
  </div>
 </div>
</div>

<div data-role="page" id="page2" class="banners">
 <div data-role="main" class="ui-content">
  <div class="patrocinadores" align="center">
      <img src="" width="100%" class="bannerPatrocinador">
  </div>
 </div>
</div>

<div data-role="page" id="page3" class="banners">
 <div data-role="main" class="ui-content">
  <div class="patrocinadores" align="center">
      <img src="" width="100%" class="bannerPatrocinador">
  </div>
 </div>
</div>



<script>
    $('.banners').on("pagecreate",function(event){

      clearInterval(trocarImagem);

        let cmpBanner1 = localStorage.getItem("cmpBanner1");
        let cmpBanner2 = localStorage.getItem("cmpBanner2");
        let cmpBanner3 = localStorage.getItem("cmpBanner3");
        let cmpLink1 = localStorage.getItem("cmpLink1");
        let cmpLink2 = localStorage.getItem("cmpLink2");
        let cmpLink3 = localStorage.getItem("cmpLink3");

        let imagens = ["adm/img/mkt/"+cmpBanner1, "adm/img/mkt/"+cmpBanner2+"", "adm/img/mkt/"+cmpBanner3+""];
        let imagemAtual = 0;
        function trocarImagem(){
          imagemAtual = (imagemAtual + 1) % 3;
          var teste = $('.bannerPatrocinador').attr('src',imagens[imagemAtual]);
        }

       setInterval(trocarImagem, 3000);

    });
</script>

1 个答案:

答案 0 :(得分:1)

您的代码中存在几个问题:

  1. clearInterval应该接受setInterval作为变量,而不是您通过setInterval调用的函数
  2. $('。bannerPatrocinador')。attr('src',IMAGE); -这会将图像添加到每个bannerPatrocinador img框中,不仅在活动页面上
  3. 由于所有内容均已加载到DOM中,因此在jquery Mobile应用程序中重用相同的类名并不明智,因此很有可能您将同时访问多个项目。
  4. 忘记jQuery Mobile,它已经死了,没有任何死灵法术可以使它复活

工作示例:http://jsfiddle.net/ws5p6nbk/

var interval;
var imagemAtual = 0;

function trocarImagem() {
  var imagens = ["https://s3.amazonaws.com/wmfeimages/wp-content/uploads/2018/09/27182802/4189366235_060e3e8e6f_z.jpg", "https://media.mnn.com/assets/images/2019/02/lexi.JPG.653x0_q80_crop-smart.jpg", "https://assets3.thrillist.com/v1/image/2709211/size/tmg-article_tall.jpg"];
  console.log(imagemAtual);
  imagemAtual = (imagemAtual + 1) % 3;
  var activePage = $.mobile.activePage;
  activePage.find('.bannerPatrocinador').attr('src', imagens[imagemAtual]);
}

$(document).on("pagecreate", '.banners', function(event) {

  clearInterval(interval);

  interval = setInterval(trocarImagem, 3000);

});

请测试这些更改,如果满意,请接受答案。