简体   繁体   中英

Generating a clickable HTML link from a javascript array

I found code online that can select and print a random name from an array, and I'm trying to modify it to print a link instead of a name. I want that link to be clickable, as it would be normally in HTML. I'm not sure how to modify the javascript to do that, however.

This was my method for doing it below. But the result is that it just prints the HTML code on the page, not an interactive link. What's the better way to do this?

let btnRandom = document.querySelector('button');
let result = document.querySelector('h1');

let links = ['https://www.nytimes.com/2019/09/19/climate/air-travel-emissions.html', 'Link2', 'Link3', 'Link4', 'Link5', 'Link6', 'Link7'];

function getRandomNumber(min, max) {
  let step1 = max - min + 1;
  let step2 = Math.random() *step1;
  let result = Math.floor(step2) + min;

  return result;
}

btnRandom.addEventListener('click', () => {
  let index = getRandomNumber(0, links.length-1);
  result.innerText = '<a href ="' + links[index] + '"</a>';
});

Result of my current code:

结果

You could use the innerHTML property instead of innerText to append the link as an actual HTML-element.

Or alternatively follow the approach mentioned here and create a link element and append it to the "result"-node.

Create an <a> element using Document.createElement() . Then append the element to the h1 node with Node.appendChild()

 let btnRandom = document.querySelector('button'); let result = document.querySelector('h1'); const links = ['https://www.nytimes.com/2019/09/19/climate/air-travel-emissions.html', 'Link2', 'Link3', 'Link4', 'Link5', 'Link6', 'Link7']; function getRandomNumber(min, max) { let step1 = max - min + 1; let step2 = Math.random() *step1; let result = Math.floor(step2) + min; return result; }; btnRandom.addEventListener('click', () => { let index = getRandomNumber(0, links.length-1); const a = document.createElement("a"); a.textContent= links[index]; a.href= links[index]; result.appendChild(a); });
 <button>Ramdom Link</button> <h1></h1>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM