随机动态插入js

场景:如下图所示。

1.需要通过js动态插入script,因为广告可能会改,所以需要动态插入;

2.由于可以接多家广告,所以需要分配展示概率。

动态插入js

这里只讲jquery的方法,getScript()

例:$.getScript("js/index.js");

更多详情

随机函数封装

// 封装随机函数
randomFn(num) {
    // num:概率
    var randomNum = Math.round(Math.random()*100);
    console.log(randomNum);
    console.log(num);
    if(randomNum < num) {
        return true
    }else {
        return false
    }
}

完整逻辑如下:

if(that.randomFn(70)) {
    //70%
    console.log(true);
}else {
    //30%
    console.log(false);
}

猜你喜欢

转载自www.cnblogs.com/lafitewu/p/9888459.html
今日推荐