簡體   English   中英

如何在JavaScript中設置`appendLink`?

[英]How do I set up `appendLink` in JavaScript?

建模后:

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

appendPre('Files:');

如何制作允許我使用appendLink('link')打印出鏈接的appendLink函數?

這是我到目前為止的內容:

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

這是一個根據給定的urltext生成鏈接(anchor元素)的函數:

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

這是將其集成到表中的方法(以我對其他問題的回答為基礎):

 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> 

您可以對鏈接的文本使用不同的參數:

 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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM