代码运行,但 HTML 内容未添加到页面

问题描述 投票:0回答:1

我正在使用“单页模型”(例如,一页 = 一个 HTML 文件)开发一个 jQuery Mobile 应用程序,并且需要显示一些广告。但是,在打开第一页后,广告不会显示在任何页面上。我添加了一些警报,因此我知道代码正在运行,只是没有输出到 HTML 内容。

这是我的 JavaScript 文件的内容:

$(document).on("pageshow", function () {
  alert("LOADED BANNER CODE");
  // Global variable that stores advertising banners.
  var ads = new Array();

  // Function that starts when the page finished loading.

  // Adds information about the new banners.
  ads.push(["http://www.dpbolvw.net/click-7490208-11465196", "http://www.lduhtrp.net/image-7490208-11465196", ""]);
  ads.push(["http://www.anrdoezrs.net/click-7490208-11646171", "http://www.ftjcfx.com/image-7490208-11646171", ""]);
  /*
  ads.push(["", "", ""]);
  ads.push(["", "", ""]);
  ads.push(["", "", ""]);
  ads.push(["", "", ""]);
  ads.push(["", "", ""]);
  ads.push(["", "", ""]);
  ads.push(["", "", ""]);
  */
  //ads.push(["http://w3schools.com/svg/default.asp", "http://adn.impactradius.com/display-ad/378-10418", "SVG"]);

  // Starting rotation with the first banner.
  ad_rotate(0);

  function ad_rotate(active) {
    alert("LOADED BANNER ADROTATE CODE");
    // Gets the div that will display banners.
    var ad_element = document.getElementById("ad");

    // Prints a new link with image in advertising box.
    ad_element.innerHTML = "<a href=\""+ads[active][0]+"\"><img src=\""+ads[active][1]+"\" alt=\""+ads[active][2]+"\" title=\""+ads[active][2]+"\" /></a>";

    // Switches to the next banner.
    active++;

    // If the counter has reached the end, it shall start again from zero.
    if(active >= ads.length) {
      active = 0;
    }

    // Run the function in 5000 milliseconds (5 seconds).
    //setTimeout("ad_rotate("+active+")", 5000);
    setTimeout(function () {ad_rotate(active);}, 5000);
  };

});

我在每个页面的头部调用它,以确保它始终被加载。该脚本在加载的第一页上运行良好,并且警报表明该脚本正在后续页面上运行。但是,在随后访问的页面上,广告就不会出现。

Firebug 在控制台中没有显示任何错误,因此脚本似乎无法找到 ID 为“ad”的 div,或者它仍在将广告添加到第一页的 div 中。

这是怎么回事,如何解决?

javascript jquery jquery-mobile
1个回答
-1
投票

HTML 按照从上到下的顺序加载内容。您可以尝试在页面底部附近加载该脚本来解决此问题。我还看到一个缩进错误。

另外,我认为您应该在运行该函数之前声明该函数,但由于您的代码正在运行,所以不需要它。此外,您可能需要每个页面有一个唯一的 ID,并且可能需要该页面的文档属性。您可以使用

document.propertyName=//something;

例如,一个常量属性编号并将其附加到广告 ID,然后在代码中将其附加到标识符。如果没有这样的情况,就只在首页展示广告,每次都会使用找到的第一个广告元素。

如果您同时拥有多个广告元素,则需要唯一的 ID 以及某种引用和查找它们的方法。您还可以在元素 id 中使用地址部分并找到它。

© www.soinside.com 2019 - 2024. All rights reserved.