我昨天开始使用 jQuery 和 JavaScript,但遇到了错误。
我想要的只是在 H1 标记之后随机放置广告(假设页面上有 10 个 H1 被 2 = 5 AdPosition 潜水)现在在随机选择的 H1 之后添加 5 个 AdBlock。
听起来很简单,但我无法做到这一点...:/ 因为 jQuery 或 myCode 只粘贴一个 AdBlock。
JsFiddle: http: //jsfiddle.net/byt3w4rri0r/eCBCK/ - 工作!
我的HTML:
<body>
<div id="content-inner">
<h1 class="headline">Headline</h1>
<h1 class="headline">Headline</h1>
<h1 class="headline">Headline</h1>
<h1 class="headline">Headline</h1>
<h1 class="headline">Headline</h1>
<h1 class="headline">Headline</h1>
<h1 class="headline">Headline</h1>
<h1 class="headline">Headline</h1>
<h1 class="headline">Headline</h1>
<h1 class="headline">Headline</h1>
</div>
</body>
MyJQUERY/JavaScript:
//count H1
var countH1 = parseFloat($("#content-inner h1").length)-1; //-1 because 0 is also a number!
//how often the ads should be displayed
var ad_count = Math.round(countH1 / 2);
//random helper
var min = 0;
var max = countH1;
//random position
for (counter = 0; counter < ad_count; counter++){
var random_position = Math.round((Math.random() * (max - min)) + min);
console.log("Random_Position:", random_position);
// paste google-code
if ($(".headline").hasClass('advertised') == true) {
random_position++;
console.log('already advertised!')
if (random_position > countH1) {
random_position--;
}
} else {
$('h1:eq('+random_position+')').append('<div class="google_ad1"></div>');
$('h1.headline').addClass('advertised');
}
}
console.log("CountH1 -1, because 0=1, 1=2,....", countH1);
console.log(werbung_anzahl);
console.log(zufall_position);
console.log(counter);