如何在Javascript字符串数组中包含超链接?

时间:2018-06-24 21:44:25

标签: javascript jquery html

我正在尝试向字符串添加超链接-并且尝试同时使用.link和.innerHTML-我认为我可能误解了我应该做的事情(这是很新的)。下面是我的代码:

<div id="typedtext"></div>
<script type="text/javascript">
// set up text to print, each item in array is new line
var aText = new Array(
"Hi, I'm Krishaan!", "A few words, wish I could add a link here", "Here are 
some words." ,"thanks a million for any help -- click here for more."
);
var iSpeed = 100; // time delay of print out
var iIndex = 0; // start printing array at this posision
var iArrLength = aText[0].length; // the length of the text array
var iScrollAt = 20; // start scrolling up at this many lines
var iTextPos = 0; // initialise text position
var sContents = ''; // initialise contents variable
var iRow; // initialise current row

function typewriter()
{
sContents =  ' ';
iRow = Math.max(0, iIndex-iScrollAt);
var destination = document.getElementById("typedtext");

while ( iRow < iIndex ) {
sContents += aText[iRow++] + '<br />';
}
destination.innerHTML = sContents + aText[iIndex].substring(0, iTextPos) + 
"_";
if ( iTextPos++ == iArrLength ) {
iTextPos = 0;
iIndex++;
if ( iIndex != aText.length ) {
iArrLength = aText[iIndex].length;
setTimeout("typewriter()", 500);
}
} else {
setTimeout("typewriter()", iSpeed);
}
}

1 个答案:

答案 0 :(得分:1)

与标准HTML一样,您只需将所需的链接包装在<a href='location'>text</a>中,同时通过JavaScript将其输出:

// set up text to print, each item in array is new line
var aText = new Array("Hi, I'm Krishaan!", "A few words, wish I could add a link here", "Here are some words.", "thanks a million for any help--click <a href='http://www.google.com'>here</a> for more.");
var iSpeed = 100; // time delay of print out
var iIndex = 0; // start printing array at this posision
var iArrLength = aText[0].length; // the length of the text array
var iScrollAt = 20; // start scrolling up at this many lines
var iTextPos = 0; // initialise text position
var sContents = ''; // initialise contents variable
var iRow; // initialise current row

function typewriter() {
  sContents = ' ';
  iRow = Math.max(0, iIndex - iScrollAt);
  var destination = document.getElementById("typedtext");

  while (iRow < iIndex) {
    sContents += aText[iRow++] + '<br />';
  }
  destination.innerHTML = sContents + aText[iIndex].substring(0, iTextPos) +
    "_";
  if (iTextPos++ == iArrLength) {
    iTextPos = 0;
    iIndex++;
    if (iIndex != aText.length) {
      iArrLength = aText[iIndex].length;
      setTimeout("typewriter()", 500);
    }
  } else {
    setTimeout("typewriter()", iSpeed);
  }
}

typewriter();
<div id="typedtext"></div>

请注意,由于数组使用双引号,因此您的超链接将需要使用单引号!