簡體   English   中英

如何在Javascript隨機文本數組中插入超鏈接?

[英]How do I insert a hyperlink into a Javascript randomizing text array?

這是代碼:

<SCRIPT LANGUAGE="Javascript"><!--

function text() {
};

text = new text();
number = 0;

// textArray        
text[number++] = "I read the other day some verses written by an eminent painter which were original and not conventional."         
text[number++] = "The soul always hears an admonition in such lines, let the subject be what it may."        
text[number++] = "The sentiment they instil is of more value than any thought they may contain."        
text[number++] = "To believe your own thought, to believe that what is in your private heart is true for all men, that is genius." 

increment = Math.floor(Math.random() * number);

document.write(text[increment]);

//--></SCRIPT>

具體來說就是我想要的單詞:

對你來說是真的

從數組中的第四個文本鏈接到某些外部網站。

<a>標記似乎不適用於我。 字符串方法也沒有。 當然,我真是個笨蛋。

我猜你的問題是與行情插入,當你使用a標簽,你應該用在適當的意義引號象下面這樣:

text[number++] = "I read the other day some verses written by an eminent painter which were original and not conventional"         
text[number++] = "The soul always hears an admonition in such lines, let the subject be what it may."        
text[number++] = "The sentiment they instil is of more value than any thought they may contain."
text[number++] = "To believe your own thought, to believe that what is in your private heart is <a href='javascript:void(0);'>true for </a> all men, that is genius." 

http://jsbin.com/luyod/2/

讓我們逐步完成此步驟,

  1. 創建一個新的var叫做iable text ,並讓它成為一個數組

     var text = []; 

    這里的[]數組文字

  2. 用您的字符串填充數組 text

     text.push("I read the other day some verses written by an eminent painter which were original and not conventional."); text.push("The soul always hears an admonition in such lines, let the subject be what it may."); text.push("The sentiment they instil is of more value than any thought they may contain."); text.push("To believe your own thought, to believe that what is in your private heart is true for all men, that is genius."; 

    在這里, someArray.push是一種將新項目添加到Array someArray 每個新項目都有其自己的索引,索引從0開始。

  3. 選擇從數組隨機指標text ,並將其分配到一個新的var iable, i

     var i = Math.floor(Math.random() * text.length); 

    JavaScript中Math.random方法返回的值嚴格小於1大於或等於0 這意味着我們可以通過項目(或長度 )的數組的數量相乘的值向上,然后向下舍入(或地板 )此數目來選擇從所述陣列的隨機索引。

  4. text 索引 i處的String中,將任何出現的"true for you"替換"true for you"的鏈接。 讓我們給這個var iable名str所以我們可以參考回去吧。

     var str = text[i].replace(/true for you/g, "<a href=\\"http://stackoverflow.com\\">true for you</a>"); 

    在這里, /true for you/g正則表達式RegExp g末代表g葉形的,意思是“繼續做下去,直到你到達終點。”

  5. 以您喜歡的方式將此新的String (我們稱為str )寫到您的#document中。 由於我們看不到與您的HTML標記有關的任何內容,因此我保留您的document.write ,但這被認為是不好的做法,因此您將來可能想學習替代方法。

     document.write(str); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM