简体   繁体   English

从 javascript 数组生成可点击的 HTML 链接

[英]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.我在网上找到了可以 select 并从数组中打印随机名称的代码,我正在尝试修改它以打印链接而不是名称。 I want that link to be clickable, as it would be normally in HTML.我希望该链接是可点击的,因为它通常在 HTML 中。 I'm not sure how to modify the javascript to do that, however.但是,我不确定如何修改 javascript 来做到这一点。

This was my method for doing it below.这是我在下面做的方法。 But the result is that it just prints the HTML但结果是它只打印了 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.您可以使用 innerHTML 属性而不是 innerText 到 append 链接作为实际的 HTML 元素。

Or alternatively follow the approach mentioned here and create a link element and append it to the "result"-node.或者,也可以按照此处提到的方法创建一个链接元素并将 append 连接到“结果”节点。

Create an <a> element using Document.createElement() .使用Document.createElement()创建一个<a>元素。 Then append the element to the h1 node with Node.appendChild()然后 append 使用Node.appendChild()将元素添加到h1节点

 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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