如何摆脱随机函数的动态链接?

我要拿出刚才的动态链接,但这里并不是所有的对象:如何摆脱随机函数的动态链接?

function random_imglink(){ 

var myimages=new Array()

//specify random images below. You can have as many as you wish

myimages[1]="/documents/templates/bilgiteknolojileri/standalone.swf"

myimages[2]="/documents/templates/bilgiteknolojileri/mobil.swf"

myimages[3]="/documents/templates/bilgiteknolojileri/3b2.swf"

var ry=Math.floor(Math.random()*myimages.length)

if (ry==0)

ry=1

document.write('<embed wmode="transparent" src="'+myimages[ry]+'" height="253" width="440"></embed>')

}

random_imglink()

我的意思是,让水木清华像$ random_link $动态链接,这样我可以把它放在HTML代码

<embed wmode="transparent" src="$random_link$" height="253" width="440"></embed> 

回答:

function randomItem(theArray) { 

return theArray[Math.floor(theArray.length * Math.random())];

}

myImages = ["some","image","paths"];

var theFlashElement = '<embed wmode="transparent" src="' + randomItem(myImages) + '" height="253" width="440"></embed>';

document.getElementById("flashContainerId").innerHTML = theFlashElement;

回答:

我很难搞清楚你问的是什么,但是如果你想从函数中获得链接(也许作为返回值),以便脱离document.write(几乎总是一个好主意摆脱),那么:

function random_imglink(){ 

var myimages=new Array()

//specify random images below. You can have as many as you wish

myimages[1]="/documents/templates/bilgiteknolojileri/standalone.swf"

myimages[2]="/documents/templates/bilgiteknolojileri/mobil.swf"

myimages[3]="/documents/templates/bilgiteknolojileri/3b2.swf"

var ry=Math.floor(Math.random()*myimages.length)

if (ry==0) {

ry=1;

}

return myimages[ry];

}

alert(random_imglink()); // alerts one of the three paths above


题外话:下面是函数清理了一些:

function random_imglink(){ 

//specify random images below. You can have as many as you wish

var myimages = [

"/documents/templates/bilgiteknolojileri/standalone.swf",

"/documents/templates/bilgiteknolojileri/mobil.swf",

"/documents/templates/bilgiteknolojileri/3b2.swf"

];

return myimages[Math.floor(Math.random()*myimages.length)];

}

alert(random_imglink()); // alerts one of the three paths above

变化:

  1. 不要依赖分号插入,你将永远无法缩小脚本(无论如何它都是魔鬼的产生)。
  2. 使用数组文字。
  3. 使用索引0..2而非1..3
  4. 作为#3的结果降低生成索引

的复杂性我没有分解出的路径的公共部分上假设可能有其他人稍后添加,但没有该公共部分(/documents/templates/bilgiteknolojileri/)。如果路径始终以此开始,那么很明显,您可以通过仅列出一次,然后追加更改的位来减小脚本的大小。

以上是 如何摆脱随机函数的动态链接? 的全部内容, 来源链接: utcz.com/qa/258845.html

回到顶部