以后,请尝试自己尝试一下,并提出更具体的问题。如果您不编写服务,我不明白您为什么不想使用服务。
但是,既然你是,这是我的建议。
Javascript:
var banners = [
{
"img": "tnl-banner-steve-jobs-01.png",
"url": "http://news.stanford.edu/news/2005/june15/jobs-061505.html",
"weight": 1
},
{
"img": "tnl-banner-steve-jobs-02.png",
"url": "http://news.stanford.edu/news/2005/june15/jobs-061505.html",
"weight": 1
},
{
"img": "tnl-banner-steve-jobs-03.png",
"url": "http://news.stanford.edu/news/2005/june15/jobs-061505.html",
"weight": 1
},
{
"img": "tnl-banner-steve-jobs-04.png",
"url": "http://news.stanford.edu/news/2005/june15/jobs-061505.html",
"weight": 1
},
{
"img": "tnl-banner-steve-jobs-05.png",
"url": "http://news.stanford.edu/news/2005/june15/jobs-061505.html",
"weight": 4
}
];
这是要添加到 HTML 中的脚本:
<script>
// Fetch the banner setup file.
var filename = getURLParameter("type")+".js";
jQuery.getScript(filename, function(){
var banner = randomBanner();
// Add the banner to the page body.
$('body').append("<a target=\"tnl_ad\" href=\""+banner["url"]+"\">" +
"<img src=\"banners/"+banner["img"]+"\"></a>");
})
.fail(function(jqxhr, settings, exception) {
console.log("Error parsing " + filename + ": " + exception.message);
}
)
function randomBanner() {
var totalWeight = 0, cummulativeWeight = 0, i;
// Add up the weights.
for (i = 0; i < banners.length; i++) {
totalWeight += banners[i]["weight"];
}
console.log("Total weight: " + totalWeight);
var random = Math.floor(Math.random() * totalWeight);
// Find which bucket the random value is in.
for (i = 0; i < banners.length; i++) {
cummulativeWeight += banners[i]["weight"];
if (random < cummulativeWeight) {
return(banners[i]);
}
}
}
function getURLParameter(name){
return decodeURI((RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]);
}
</script>
Source