如何使用JavaScript创建链接?

173

我有一个标题的字符串和一个链接的字符串。我不确定如何使用JavaScript将它们组合在一起,创建一个链接放置在页面上。感谢任何帮助。

我尝试弄清楚这个问题的原因是我有一个RSS源,其中有一系列的标题和URL。我想将标题链接到相应的URL以使页面更有用。

我正在使用jQuery,但完全不熟悉它,并不知道它可以在这种情况下提供帮助。


你是用jQuery或其他库(Mootools、Dojo、Atlas等)加载RSS源吗?如果你想要根据在页面加载时获取的第三方RSS列表动态创建锚点标签,我建议使用jQuery库或其他库来添加元素。在这种情况下,了解细节非常重要,以确定需要做什么。然而,DOM方法是一个有用的示例。 - Jared Farrish
尝试这个链接,我认为它会有益。 - Yitzhak Weinberg
8个回答

285
<html>
  <head></head>
  <body>
    <script>
      var a = document.createElement('a');
      var linkText = document.createTextNode("my title text");
      a.appendChild(linkText);
      a.title = "my title text";
      a.href = "http://example.com";
      document.body.appendChild(a);
    </script>
  </body>
</html>

1
这是一个使用DOM方法向页面添加锚点标签的非常通用的示例。例如,appendChild方法可以是页面内的列表元素、TD或其他元素。请参见:http://www.quirksmode.org/ - Jared Farrish
16
@Nadu - 请停止编辑我的回答。如果你想要表达某个具体的内容,请添加你自己的回答;如果那个内容并不足够“不同”以至于需要修改,那么就没有必要进行编辑。 - Jared Farrish
我已经创建了一个 Plunker 示例。https://plnkr.co/edit/mV7nOBIHa6hMNaVIPG75?p=preview - Harold Castillo

69

使用JavaScript

  1. var a = document.createElement('a');
    a.setAttribute('href',desiredLink);
    a.innerHTML = desiredText;
    // apend the anchor to the body
    // of course you can append it almost to any other dom element
    document.getElementsByTagName('body')[0].appendChild(a);
    
  2. document.getElementsByTagName('body')[0].innerHTML += '<a href="'+desiredLink+'">'+desiredText+'</a>';
    

    or, as suggested by @travis :

    document.getElementsByTagName('body')[0].innerHTML += desiredText.link(desiredLink);
    
  3. <script type="text/javascript">
    //note that this case can be used only inside the "body" element
    document.write('<a href="'+desiredLink+'">'+desiredText+'</a>');
    </script>
    

使用 JQuery

  1. $('<a href="'+desiredLink+'">'+desiredText+'</a>').appendTo($('body'));
    
  2. $('body').append($('<a href="'+desiredLink+'">'+desiredText+'</a>'));
    
  3. var a = $('<a />');
    a.attr('href',desiredLink);
    a.text(desiredText);
    $('body').append(a);
    
在上述所有示例中,您可以将锚点附加到任何元素,而不仅仅是 'body',desiredLink 是一个变量,它保存您的锚点元素指向的地址,desiredText 是一个变量,它保存将显示在锚点元素中的文本。

3
我认为你漏掉了一个:document.getElementsByTagName('body')[0].innerHTML += desiredText.link(desiredLink);。它的意思是在网页中添加一个链接,链接的文字是desiredText,链接的地址是desiredLink - travis
1
为了避免 XSS 攻击,构建 HTML 时应避免使用字符串连接(+)和.innerHTML。在 jQuery 中,.attr("href", desiredLink).text(desiredText) 是您想要的。 - Wes Turner

20

使用JavaScript创建链接:

<script language="javascript">
<!--
document.write("<a href=\"www.example.com\">");
document.write("Your Title");
document.write("</a>");
//-->
</script>

或者

<script type="text/javascript">
document.write('Your Title'.link('http://www.example.com'));
</script>

或者

<script type="text/javascript">
newlink = document.createElement('a');
newlink.innerHTML = 'Google';
newlink.setAttribute('title', 'Google');
newlink.setAttribute('href', 'http://google.com');
document.body.appendChild(newlink);
</script>

16

有几种方法:

如果你想使用原生JavaScript(没有像jQuery这样的帮助程序),那么可以这样做:

var link = "http://google.com";
var element = document.createElement("a");
element.setAttribute("href", link);
element.innerHTML = "your text";

// and append it to where you'd like it to go:
document.body.appendChild(element);

另一种方法是将链接直接写入文档中:

document.write("<a href='" + link + "'>" + text + "</a>");

我肯定更喜欢第一个选项。为此点赞,但混合JS和HTML会混淆内容和行为,这两者应该分开。如果过度使用,这可能会导致维护方面的噩梦。 - jamesmortensen
我也倾向于选择第一种选项,但或许可以使用JQuery来实现相同的效果(提高可读性和易维护性)。 - Roopinder
1
你应该避免使用document.write https://dev59.com/ulLTa4cB1Zd3GeqPeOL_ - TryHarder

5
使用原生JavaScript动态创建超链接:
   var anchorElem = document.createElement('a');
   anchorElem.setAttribute("href", yourLink);
   anchorElem.innerHTML = yourLinkText;

   document.body.appendChild(anchorElem); // append your new link to the body

1
使用 anchorElem.text = yourLinkText; 而不是 innerHTML,这样会更清晰。当然,考虑一下如果 yourLinkText 是 " <- 酷!" 会发生什么。 - Nadu

5

    <script>
      _$ = document.querySelector  .bind(document) ;

        var AppendLinkHere = _$("body") // <- put in here some CSS selector that'll be more to your needs
        var a   =  document.createElement( 'a' )
        a.text  = "Download example" 
        a.href  = "//bit\.do/DeezerDL"

        AppendLinkHere.appendChild( a )
        

     // a.title = 'Well well ... 
        a.setAttribute( 'title', 
                         'Well well that\'s a link'
                      );
    </script>

  1. 'Anchor Object'有自己(继承的)属性来设置链接和文本。所以只需要使用它们。 setAttribute 更通用,但通常不需要使用它。 a.title ="Blah" 将执行相同的操作并且更加清晰! 当需要使用setAttribute的情况是: var myAttrib = "title"; a.setAttribute( myAttrib , "Blah")

  2. 保持协议开放。 不要使用 http://example.com/path,而应该直接使用 //example.com/path。 检查 example.com 是否可以通过 http:https: 访问,但 95% 的站点都可以正常工作。

  3. 离题:这与在JS中创建链接没有关系, 但也许值得知道: 有时候你可以使用 $("body") 而不是 document.querySelector("body"),比如在Chrome dev-console中。 _ $ = document.querySelector 将在第一次使用时出现“非法调用”错误。这是因为赋值只是“抓取” .querySelector(对class方法的引用)。使用 .bind(... 将涉及上下文(在这里是document),并获得一个像您预期的对象方法。


0

创建元素的一种快速不太规范的方法:


const linkHTML = `<a
  class="my-link"
  style="position: absolute; right: 0"
  href="https://old.reddit.com"
  title="Go to old reddit"
>
  Old Reddit
</a>`;

  // create element
  const linkEl = strToElement(linkHTML);

  // add element to document.body
  document.body.appendChild(linkEl);

// utility function that converts a string to HTML element
function strToElement(s) {
  let e = document.createElement('div');
  const r = document.createRange();
  r.selectNodeContents(e);
  const f = r.createContextualFragment(s);
  e.appendChild(f);

  e = e.firstElementChild;
  return e;
}


-7
你需要将以下内容复制到代码中:

<A HREF = "index.html">点击这里</A>


OP明确要求使用JavaScript创建链接(而不是HTML)! - hatef

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接