jQuery(document).ready(function(){
var insertionTemplate = jQuery(".hiddenAdBox").eq(0).html(),
insertionTarget = jQuery('ul'),
insertionTargetChildren = insertionTarget.find('li'),
insertionFrequency = 2;
var random;
for (var i = 0; i < insertionFrequency; i++) {
random = Math.floor(Math.random() * insertionTargetChildren.length) + 0;
insertionTargetChildren.eq(random).after(insertionTemplate);
}
});我有项目列表,也需要在刷新页面时随机显示广告。现在,当广告数量为2 (insertionFrequency = 2)时,它们会出现在彼此之间,但不应该如此。我怎样才能发现它,而不让广告出现在彼此附近?
附上截图:


发布于 2015-09-24 05:35:43
要防止ads 水平,您可以这样做:
for (var i = 0; i < insertionFrequency; i++) {
random = Math.floor(Math.random() * insertionTargetChildren.length) + 0;
if(insertionTargetChildren.eq(random).next('.placeforad').length || insertionTargetChildren.eq(random).prev('.placeforad').length)
//check whether its previous li or next li has ad with class .placeforad
{
i--; //decrease the count so as to come up with separate random number
}
else
insertionTargetChildren.eq(random).after(insertionTemplate);
} 但是对于垂直预防,因为在每一行中没有相等数量的平方,比如第1行和第2行有3个块,最后一行只有2个,因此识别水平非常困难。如果有相等数量的平方,那么也可以采取某种方法来实现这一点。
更新
由于您同意连续三个街区,下面的代码将避免获得广告horizontally和垂直
小型演示
for (var i = 0; i < insertionFrequency; i++) {
random = Math.floor(Math.random() * insertionTargetChildren.length) + 0;
var currentElement=insertionTargetChildren.eq(random);
var addedElement=$('li.placeforad:visible');
if(currentElement.next('.placeforad').length || currentElement.prev('.placeforad').length)
{
i--;
}
else
{
if(i!=0)
{
if(addedElement.index() > currentElement.index() &&
(addedElement.index() - currentElement.index())==3)
{
i--;
}
else if(currentElement.index() - (addedElement.index()-1)==3)
{
i--;
}
else
{
insertionTargetChildren.eq(random).after(insertionTemplate);
}
}
else
insertionTargetChildren.eq(random).after(insertionTemplate);
}
} https://stackoverflow.com/questions/32753900
复制相似问题