如何在Javascript随机化文本数组中插入超链接?

时间:2014-04-14 18:40:07

标签: javascript arrays hyperlink random-sample

以下是代码:

<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>标记对我来说似乎不起作用。字符串方法也不是。当然,我是一个完全不知所措的人。

2 个答案:

答案 0 :(得分:0)

我猜您的问题与使用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 :(得分:0)

让我们一步一步地完成这个步骤,

  1. 创建一个名为var的新text iable,并将其设为 Array

    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是一种向数组 someArray添加新的方法。每个新项目都会获得它自己的索引,索引从0开始。

  3. 数组 text中选择一个随机索引,并将其分配给新的var iable,i

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

    JavaScript 中,方法Math.random返回的值严格小于1 大于或等于{{1} }} 的。这意味着我们可以将值乘以数组的项目数(或长度),然后向下舍入(或 floor )用于从数组中选择随机索引的数字。

  4. 0索引 i字符串中,将text的任何内容替换为您的链接。让我们给出"true for you"名称var,以便我们可以参考它。

    str

    此处var str = text[i].replace(/true for you/g, "<a href=\"http://stackoverflow.com\">true for you</a>"); regular expression RegExp 。最后的/true for you/g代表g,并且意味着&#34;继续这样做直到你到达终点&#34;。

  5. 以您喜欢的方式将此新字符串(我们称之为g)写入 #document 。由于我们无法看到与您的 HTML 标记相关的任何内容,因此我会保留您的str,但这被视为bad practice,因此您可以选择其他选项#39;我想在将来了解。

    document.write