如何使用 JavaScript 创建链接?

发布于 2024-10-13 19:56:07 字数 189 浏览 3 评论 0原文

我有一个标题字符串和一个链接字符串。我不知道如何将两者放在一起以使用 JavaScript 在页面上创建链接。任何帮助表示赞赏。

我试图解决这个问题的原因是因为我有一个 RSS 源并且有一个标题和 URL 列表。我想将标题链接到 URL 以使该页面有用。

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

I have a string for a title and a string for a link. I'm not sure how to put the two together to create a link on a page using JavaScript. Any help is appreciated.

The reason I'm trying to figure this out is because I have an RSS feed and have a list of titles ands URLs. I would like to link the titles to the URL to make the page useful.

I am using jQuery but am completely new to it and wasn't aware it could help in this situation.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

九歌凝 2024-10-20 19:56:07
<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>
<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>
谁的年少不轻狂 2024-10-20 19:56:07

使用 JavaScript

  1. var a = document.createElement('a');
    a.setAttribute('href',desiredLink);
    a.innerHTML =desiredText;
    // 将锚点附加到主体
    // 当然你几乎可以将它附加到任何其他 dom 元素
    document.getElementsByTagName('body')[0].appendChild(a);
    
  2. document.getElementsByTagName('body')[0].innerHTML += ''+desiredText+'';
    

    或者,按照@travis的建议:

    document.getElementsByTagName('body')[0].innerHTML +=desiredText.link(desiredLink);
    

使用 JQuery

  1. $(''+desiredText+'').appendTo($('body '));
    
  2. $('body').append($(''+desiredText+'') );
    
  3. var a = $('');
    a.attr('href',desiredLink);
    a.text(所需文本);
    $('body').append(a);
    

在上述所有示例中,您可以将锚点附加到任何元素,而不仅仅是“主体”,并且 desiredLink 是一个变量,用于保存锚点元素的地址指向,desiredText 是一个变量,用于保存将在锚元素中显示的文本。

With 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>
    

With 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);
    

In all the above examples you can append the anchor to any element, not just to the 'body', and desiredLink is a variable that holds the address that your anchor element points to, and desiredText is a variable that holds the text that will be displayed in the anchor element.

知你几分 2024-10-20 19:56:07

使用 JavaScript 创建链接:

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

OR

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

OR

<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>

Create links using JavaScript:

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

OR

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

OR

<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>
始终不够爱げ你 2024-10-20 19:56:07

有几种方法:

如果您想使用原始 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>");

There are a couple of ways:

If you want to use raw Javascript (without a helper like JQuery), then you could do something like:

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);

The other method is to write the link directly into the document:

document.write("<a href='" + link + "'>" + text + "</a>");
彻夜缠绵 2024-10-20 19:56:07

使用原始 JavaScript 动态创建超链接:

   var anchorElem = document.createElement('a');
   anchorElem.setAttribute("href", yourLink);
   anchorElem.innerHTML = yourLinkText;

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

Dynamically create a hyperlink with raw JavaScript:

   var anchorElem = document.createElement('a');
   anchorElem.setAttribute("href", yourLink);
   anchorElem.innerHTML = yourLinkText;

   document.body.appendChild(anchorElem); // append your new link to the body
慕烟庭风 2024-10-20 19:56:07
    <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. “锚对象”有自己的*(继承的)*属性,用于设置链接及其文本。所以就用它们吧。 .setAttribute 更通用,但通常不需要它。 a.title ="Blah" 也会做同样的事情并且更清晰!
    需要 .setAttribute 的情况是这样的: var myAttrib = "title"; a.setAttribute( myAttrib , "Blah")

  2. 保持协议打开。
    考虑只使用 //example.com/path,而不是 http://example.com/path。
    检查 example.com 是否可以通过 http: 以及 https: 访问,但 95% 的网站可以在这两种方式上运行。

  3. OffTopic:这与在 JS 中创建链接无关
    但也许很高兴知道:

    有时就像在 chrome 开发控制台中,您可以使用 $("body") 而不是 document.querySelector("body") A _$ = document .querySelector将在您第一次使用它时通过非法调用错误来“尊重”您的努力。这是因为赋值只是“抓取”.querySelector(对 class 方法的引用)。使用.bind(...),您还将涉及上下文(这里是document),并且您将获得一个可以工作的object方法正如您所期望的那样。

    <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. The 'Anchor Object' has its own*(inherited)* properties for setting the link, its text. So just use them. .setAttribute is more general but you normally don't need it. a.title ="Blah" will do the same and is more clear!
    Well a situation that'll demand .setAttribute is this: var myAttrib = "title"; a.setAttribute( myAttrib , "Blah")

  2. Leave the protocol open.
    Instead of http://example.com/path consider to just use //example.com/path.
    Check if example.com can be accessed by http: as well as https: but 95 % of sites will work on both.

  3. OffTopic: That's not really relevant about creating links in JS
    but maybe good to know:

    Well sometimes like in the chromes dev-console you can use $("body") instead of document.querySelector("body") A _$ = document.querySelectorwill 'honor' your efforts with an Illegal invocation error the first time you use it. That's because the assignment just 'grabs' .querySelector (a ref to the class method). With .bind(... you'll also involve the context (here it's document) and you get an object method that'll work as you might expect it.

甜味超标? 2024-10-20 19:56:07

一种肮脏快速的创建元素的方法:


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

A dirty but quick way to create elements:


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

怀里藏娇 2024-10-20 19:56:07

将其粘贴到里面:

Click here

You paste this inside :

<A HREF = "index.html">Click here</A>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文