简体   繁体   English

如何使用 javascript 创建链接?

[英]How do I create a link using javascript?

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.我不确定如何将两者放在一起使用 Javascript 在页面上创建链接。 Any help is appreciated.任何帮助表示赞赏。

EDIT1: Adding more detail to the question. EDIT1:为问题添加更多细节。 The reason I'm trying to figure this out is because I have an RSS feed and have a list of titles ands URLs.我试图弄清楚这一点的原因是因为我有一个 RSS 提要和一个标题和 URL 列表。 I would like to link the titles to the URL to make the page useful.我想将标题链接到 URL 以使页面有用。

EDIT2: I am using jQuery but am completely new to it and wasn't aware it could help in this situation. EDIT2:我正在使用 jQuery,但对它完全陌生,不知道它在这种情况下会有所帮助。

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

With JavaScript使用 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 :或者,正如@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使用 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.在上述所有示例中,您可以将锚附加到任何元素,而不仅仅是“主体”,并且desiredLink是一个变量,用于保存您的锚元素指向的地址,而desiredText是一个变量,用于保存将要发送的文本显示在锚元素中。

Create links using JavaScript:使用 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>

There are a couple of ways:有几种方法:

If you want to use raw Javascript (without a helper like JQuery), then you could do something like:如果您想使用原始 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);

The other method is to write the link directly into the document:另一种方法是将链接直接写入文档中:

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

 <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\'sa link' ); </script>

  1. The 'Anchor Object' has its own*(inherited)* properties for setting the link, its text. 'Anchor Object' 有它自己的*(inherited)* 属性来设置链接,它的文本。 So just use them.所以只需使用它们。 .setAttribute is more general but you normally don't need it. .setAttribute更通用,但您通常不需要它。 a.title ="Blah" will do the same and is more clear! a.title ="Blah"会做同样的事情,而且更清楚! Well a situation that'll demand .setAttribute is this: var myAttrib = "title"; a.setAttribute( myAttrib , "Blah")那么需要.setAttribute的情况是这样的: var myAttrib = "title"; a.setAttribute( myAttrib , "Blah") 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.而不是http://example.com/path考虑只使用 //example.com/path。 Check if example.com can be accessed by http: as well as https: but 95 % of sites will work on both.检查 example.com 是否可以通过http:https:访问,但 95 % 的网站都可以在两者上运行。

  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.querySelector will 'honor' your efforts with an Illegal invocation error the first time you use it. OffTopic:这与在 JS 中创建链接并不真正相关,但也许很高兴知道:有时就像在 chrome 开发控制台中,您可以使用$("body")而不是document.querySelector("body") A _$ = document.querySelector将在您第一次使用它时以非法调用错误“尊重”您的努力。 That's because the assignment just 'grabs' .querySelector (a ref to the class method).那是因为分配只是“抓取” .querySelector (对方法的引用)。 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.使用.bind(...您还将涉及上下文(这里是document ),并且您将获得一个可以按预期工作的对象方法。

Dynamically create a hyperlink with raw JavaScript:使用原始 JavaScript 动态创建超链接:

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

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

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

你把它贴在里面:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在javascript中创建到pdf的链接? - How do I create a link to a pdf in javascript? 我需要使用带有奇怪的 Google 电子表格链接的 Javascript 创建一个 HTML 表格。 我该怎么做呢? - I need to create an HTML table using Javascript with a weird Google Spreadsheet link. How do I do this? 如何在使用javascript的图片中使用指定的链接组创建随机链接? - How do I create a random link out of specified group of links using within an image using javascript? 使用JavaScript时,如何创建自动单击链接并在新标签页中打开它的代码? - When using JavaScript, how do I create code that automatically clicks a link and opens it in a new tab? 如何在 Javascript 中不显示 URL 的情况下创建链接? - How do I create a link without the URL being visible in Javascript? 如何创建指向页面的链接并强制它立即执行 javascript - How do I create a link to a page and force it to immediately execute a javascript 如何使用JavaScript创建rss / xml链接元素 - How do you create an rss/xml link element using javascript 如何使用javascript创建此效果? - How do i create this effect using javascript? 如何在Angular 2 / Ionic 2中使用插值创建链接标签 - How do I create link tag using interpolation in Angular 2 / Ionic 2 如何使用javascript附加li和link元素 - How do I append an li and link elements using javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM