如何在JavaScript中设置`appendLink`? [英] How do I set up `appendLink` in JavaScript?

查看:96
本文介绍了如何在JavaScript中设置`appendLink`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

建模之后:

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

appendPre('Files:');

如何制作 appendLink 函数允许我使用 appendLink('link')打印出一个链接?

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

这就是我所拥有的far:

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';
}


推荐答案

这是一个生成函数来自给定 url 文本的链接(锚元素)

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>

这篇关于如何在JavaScript中设置`appendLink`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆