简体   繁体   中英

using js/jquery to populate google adsense

I am trying to incorporate my own advertisement module for my website, if their are no ads to be displayed it defaults to google adesense ad

I currently have

if(this.ad_found)
//run code to display ad
else {
    google_ad_client = "ca-pub-";
    /* Name */
    google_ad_slot = "-----";
    google_ad_width = ---;
    google_ad_height = ---;

    var head = document.getElementById('id_from_display_page')[0];
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = '//pagead2.googlesyndication.com/pagead/show_ads.js';
    $("#id_from_display_page").html(script);
}

as you can tell I have no idea how to populate id 'id_from_display_page' to display the google adsense stuff

The display page:

<div id="id_from_display_page"></div>

I want to populate this div with google adsense

EDITS:

This time, we're going to wrap all of this in a self-executing function. Also, we'll make new elements and stick em in the body at the end. Here's the cheat sheet:

Javascript:

(function (window, document) {
    if (ad_found) {
        //run code to display ad
    } else {
        google_ad_client = "ca-pub-";
        /* Name */
        google_ad_slot = "-----";
        google_ad_width = "---";
        google_ad_height = "---";

        var head = document.createElement('div');
        head.id = "id_from_display_page";
        var script = '<script src="//pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"><\/script>';
        head.innerHTML = script;
        document.body.appendChild(head);
    }
})(this, this.document, undefined);

Unfortunately without those variables set I have no way of actually testing this. But I decided to place the <script> inside of a new <div> element that would have to get parsed by the DOM and should result in the code being executed as expected.

Keep me posted.

Besides the missing variables, everything seems smooth with the fiddle I made below :)

Demooooooooo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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