如何用<script>标签动态广告div,包括内联JS以便这个JS执行?</script>

时间:2012-01-31 23:54:05

标签: javascript google-dfp

我在尝试动态添加和执行包含内联Javascript的div时遇到问题?

var div = document.createElement('DIV');                
div.onready = (function(name) { return GA_vitalFillSlot(name); })(wallpaper_ads.custom[i]);
document.getElementById('wallpaperAdContainer').appendChild(div);

其中wallpaper_ads.custom[i]包含字符串,例如'BMX_wallpaper_2328x1080_homepage'。 上面的代码不起作用。但是,如果我将GA_vitalFillSlot()更改为alert()

,则会有效
var div = document.createElement('DIV');                
div.onready = (function(name) { return alert(name); })(wallpaper_ads.custom[i]);
document.getElementById('wallpaperAdContainer').appendChild(div);

此外,做这样的事情也不起作用:

var js = document.createElement('SCRIPT');
js.type = 'text/javascript';
js.innerHTML = 'GA_vitalFillSlot("'+wallpaper_ads.custom[i]+'");';
document.getElementById('wallpaperAdContainer').appendChild(js);

这里有什么问题吗?

3 个答案:

答案 0 :(得分:1)

或者:

js.src = 'myCode.js';

js.text = 'alert("hey");';

使用innerHTML插入的脚本无法执行。

答案 1 :(得分:1)

这行代码:

(function(name) { return GA_vitalFillSlot(name); })(wallpaper_ads.custom[i]);

正在立即执行div.onready设置等于GA_vitalFillSlot(name)的结果。更改它,以便onready指向一个函数:

div.onready = (function(name) { 
    return function() {
        GA_vitalFillSlot(name);
    };
})(wallpaper_ads.custom[i]);

答案 2 :(得分:0)

这应该有效

js.src = 'GA_vitalFillSlot("'+wallpaper_ads.custom[i]+'");';
相关问题