萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 動態創建超鏈接:createElement 實戰

核心代碼

function AppendLink() {
    var div = document.getElementById("divMain");
    var linkTmp = document.createElement("a");
    linkTmp.href = "https://www.baidu.com";
    linkTmp.innerText = "百度"; // 鏈接文本用 innerText/textContent
    div.appendChild(linkTmp);
}

關鍵點提示

  • <a> 元素無 value 屬性,文本內容用 innerText 或 textContent 設置。
  • href 屬性直接賦值字符串。
  • 可同步設置 target="_blank"、rel="noopener" 等屬性增強安全性。

現代化寫法

function appendLink(url, text, containerId) {
    const container = document.getElementById(containerId);
    const a = document.createElement('a');
    a.href = url;
    a.textContent = text;
    a.target = '_blank';
    a.rel = 'noopener noreferrer';
    container.appendChild(a);
}

// 使用
appendLink('https://example.com', '示例鏈接', 'divMain');

批量創建優化

const links = [
    {url: 'https://a.com', text: 'A站'},
    {url: 'https://b.com', text: 'B站'}
];
const fragment = document.createDocumentFragment();
links.forEach(({url, text}) => {
    const a = document.createElement('a');
    a.href = url;
    a.textContent = text;
    fragment.appendChild(a);
});
document.getElementById('divMain').appendChild(fragment);
copyright © 萬盛學電腦網 all rights reserved