-1

如何将 Adsense 广告放入 javascript 标签中?

<script type="text javascript">
var ad = "<script type="text/javascript"><!--
          google_ad_client = "ca-pub-12345";
          google_ad_slot = "12345";
          google_ad_width = 728;
          google_ad_height = 90;
          //-->
          </script>
          <script type="text/javascript"
          src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
          </script>";
</script>

以上显然是行不通的。但是,它展示了我正在尝试做的事情。任何人都可以弄清楚如何有效地做到这一点?谢谢。

更新 这仍然给我一个语法错误

var ad = "<script type='text/javascript'><!--
                            google_ad_client = 'ca-pub-12345';
                            /* plastic surgery body large banner */
                            google_ad_slot = '12345';
                            google_ad_width = 728;
                            google_ad_height = 90;
                            //-->
                            </script>
                            <script type='text/javascript'
                            src='http://pagead2.googlesyndication.com/pagead/show_ads.js'>
                            </script>";
4

1 回答 1

0

嗯,第一部分是您的发布者身份信息。那只是脚本,所以要么直接放入:

google_ad_client = "ca-pub-12345";
google_ad_slot = "12345";
google_ad_width = 728;
google_ad_height = 90;

...或者您可以使用 eval:

var ad = [
  'google_ad_client = "ca-pub-12345";',
  'google_ad_slot = "12345";',
  'google_ad_width = 728;',
  'google_ad_height = 90;' ].join('');
eval(ad);

document.write()可用于创建<script>标签,但要注意:MSIE 有一个扫描单词的错误,<script>因此请始终将其分解为表达式:

<script>
document.write('<scr'+ 'ipt type="text/javascript" ');
document.write(' src="http://pagead2.googlesyndication.com/pagead/show_ads.js">');
document.write('</scri' + ' ipt>');
</script>

实际上,如果您已经将所有内容都放入ad变量中,您可以简单地:

document.write(ad);

您可能遇到的唯一问题是您不能通过 Ajax 调用来执行此操作。如果您使用的是jQuery,则可以执行以下操作:

$.ajax('//host/my/tag.js', {
  dataType: 'text',
  success: function(text) {
    $('#target-id').html(text);
  }
});

jQuery 将自动计算出如何将脚本标签激活到这些位置,但这可能不适用于某些类型的富媒体广告素材。

于 2012-10-06T17:56:52.797 回答