2010-12-10 20 views
0

我要拿出剛纔的動態鏈接,但這裏並不是所有的對象:如何擺脫隨機函數的動態鏈接?

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> 
+0

目前還不清楚你在問什麼。你想獲得一個返回值或一些這樣的? – 2010-12-10 14:06:09

+0

我的意思是,現在func的工作是這樣的,它把整個嵌入對象,但我希望它只寫動態鏈接,這樣我就可以把它放在另一個對象的scipt – 2010-12-10 14:07:55

回答

0
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; 
+0

請注意,你需要一個

在你的文檔中來做到這一點工作 – 2010-12-10 14:19:28

0

我很難搞清楚你問的是什麼,但是如果你想從函數中獲得鏈接(也許作爲返回值),以便脫離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/)。如果路徑始終以此開始,那麼很明顯,您可以通過僅列出一次,然後追加更改的位來減小腳本的大小。

+0

不,我不想鏈接只是爲了顯示鏈接,或者做一個動態鏈接代碼 – 2010-12-10 14:12:19

+1

@venom:警報只是爲了告訴你函數返回的內容。一旦你有了函數的返回值,你可以用它做你喜歡的事情 - 輸出一個'embed'標籤,把它放在一個鏈接等等。 – 2010-12-10 14:15:16