How do I set up `appendLink` in JavaScript?

ぐ巨炮叔叔 提交于 2019-12-31 05:31:11

问题


Modeling after:

function appendPre(message) {
    var pre = document.getElementById('content');
    var textContent = document.createTextNode(message + '\n');
    pre.appendChild(textContent);
}

appendPre('Files:');

How do I make an appendLink function that allows me to use appendLink('link') to print out a link?

This is what I have so far:

function appendLink(url) {
  var link = document.createElement('a');
  var textContent = document.createTextNode(url + '\n');
  link.appendChild(textContent);
  link.href = 'test.com';
}

回答1:


Here is a function to generate a link (anchor element) from a given url and text:

function link (url, text) {
  var a = document.createElement('a')
  a.href = url
  a.textContent = text || url
  return a
}

Here is how you can integrate it into your table (building on my answer to your other question):

function link (url, text) {
  var a = document.createElement('a')
  a.href = url
  a.textContent = text || url
  return a
}

function appendRow (table, elements, tag) {
  var row = document.createElement('tr')
  elements.forEach(function(e) {
    var cell = document.createElement(tag || 'td')
    if (typeof e === 'string') {
      cell.textContent = e
    } else {
      cell.appendChild(e)
    }

    row.appendChild(cell)
  })
  table.appendChild(row)
}


var file = {
  name: 'hello',
  viewedByMeTime: '2017-03-11T01:40:31.000Z',
  webViewLink: 'http://drive.google.com/134ksdf014kldsfi0234lkjdsf0314/',
  quotaBytesUsed: 0
}


var table = document.getElementById('content')

// Create header row
appendRow(table, ['Name', 'Date', 'Link', 'Size'], 'th')

// Create data row
appendRow(table, [
  file.name,
  file.viewedByMeTime.split('.')[0],
  link(file.webViewLink), // Note the enclosing call to `link`
  file.quotaBytesUsed + ' bytes'
])
#content td,
#content th {
  border: 1px solid #000;
  padding: 0.5em;
}

#content {
  border-collapse: collapse;
}
<table id="content">
</table>



回答2:


You can just use a different parameter for the link's text:

function appendLink(target, url, text) {
  var link = document.createElement('a');
  var textContent = document.createTextNode(text);
  link.appendChild(textContent);
  link.href = url;
  target.appendChild(link);
}
var link = document.getElementById('link');
appendLink(link, '//stackoverflow.com', 'Link to Stackoverflow');
<div id="link"></div>


来源:https://stackoverflow.com/questions/42730172/how-do-i-set-up-appendlink-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!