首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >不要让广告出现在彼此之间,jquery

问不要让广告出现在彼此之间,jquery
EN

Stack Overflow用户
提问于 2015-09-24 05:21:22
回答 1查看 43关注 0票数 1

这是我的演示

代码语言:javascript
复制
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)时,它们会出现在彼此之间,但不应该如此。我怎样才能发现它,而不让广告出现在彼此附近?

附上截图:

​

​

​

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-09-24 05:35:43

要防止ads 水平,您可以这样做:

代码语言:javascript
复制
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和垂直

小型演示

代码语言:javascript
复制
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);
    }
} 
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32753900

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档