javascript - 根据$(document).width()加载Google广告代码

标签 javascript jquery

正在实现 Google Ads,但尝试根据 $(document).width() 提供两个广告脚本之一。

尽我所能地阅读和搜索,到目前为止我所得到的内容似乎没有损坏(没有明显的错误),只是它实际上没有插入 Google 广告。 (是的,错过了重点!)

首先,我设置放置广告的区域:

<div id="google-ad"></div>

随后通过逻辑确定文档宽度,并插入必要的 Google Ad 脚本:

if ( $(document).width() < 728 ) {
    $("#google-ad").html('<script type="text/javascript"><!--google_ad_client = "ca-pub-GOOGLE-ID";/* AD NAME HERE */google_ad_slot = "GOOGLE-NUMBER"; google_ad_width = 320; google_ad_height = 50;//--><\/script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"><\/script>');
} else {
$("#google-ad").html('<script type="text/javascript"><!--google_ad_client = "ca-pub-GOOGLE-ID";/* AD NAME HERE */google_ad_slot = "GOOGLE-NUMBER"; google_ad_width = 728; google_ad_height = 90;//--><\/script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"><\/script>');
                });

理论上,我认为这可行,但实际上行不通。所以,我肯定做错了什么。欢迎任何帮助或指导。

谢谢。

最佳答案

你说确定文档宽度的逻辑是在你想要插入的div之后,这让我相信DOM还没有准备好并且你没有得到宽度(可能是未定义的),在这种情况下,只需在触发就绪事件后调用逻辑,或者如果您想等待图像等加载,则使用 .load 这可能会改变文档宽度

$(document).ready(function () {
    //put your ad load logic here.
});

关于javascript - 根据$(document).width()加载Google广告代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13774504/

相关文章:

javascript - 计算 Google 表格脚本中的粗体单元格

javascript - 当页面加载为 iFrame 时禁用 GTM 标记触发

javascript - jquery克隆输入文件在克隆div时没有添加文件

javascript - 在 div 下方对齐 anchor 标记

javascript - Ajax函数不发送数据onclick

php - 允许网络用户使用 PHP 和 Javascript 更新文本文件的最简单方法?

javascript - Highcharts - 某些系列的共享工具提示

javascript - 根据数组或对象项的数量设置背景图像

javascript - 如何遍历列表并添加图像

javascript - 如何在ajax上重新加载数据表并触发新的分页