Jak utworzyć link za pomocą javascript?

Mam ciąg znaków dla tytułu i ciąg znaków dla linku. Nie jestem pewien, jak połączyć te dwa elementy, aby utworzyć link na stronie za pomocą Javascript. Każda pomoc jest mile widziana.

EDIT1: dodanie więcej szczegółów do pytania. Powodem, dla którego próbuję to rozgryźć, jest to, że mam kanał RSS i mam listę tytułów i adresów URL. Chciałbym połączyć tytuły z adresem URL, aby strona była użyteczna.

EDIT2: używam jQuery, ale jestem w nim zupełnie nowy i nie wiedziałem, że może pomoc w tej sytuacji.

Author: Xavier, 2011-01-23

7 answers

<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>
 181
Author: Jared Farrish,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-30 17:34:59

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

    Lub, zgodnie z sugestią @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>
    

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

We wszystkich powyższych przykładach możesz dodać kotwicę do dowolnego elementu, a nie tylko do "body", a {[7] } jest zmienną, która przechowuje adres, na który wskazuje Twój element kotwicy, a {[8] } jest zmienną, która przechowuje tekst, który będzie wyświetlane w elemencie kotwicy.

 44
Author: gion_13,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 10:31:31

Tworzenie linków przy użyciu JavaScript:

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

Lub

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

Lub

<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>
 12
Author: Naveed,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-01-24 22:58:41

Jest kilka sposobów:

Jeśli chcesz używać surowego Javascript (bez helpera jak JQuery), możesz zrobić coś takiego jak:

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

Inną metodą jest zapisanie linku bezpośrednio do dokumentu:

document.write("<a href='" + link + "'>" + text + "</a>");
 8
Author: Roopinder,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-01-23 07:52:27

Dynamicznie Utwórz hiperłącze z surowym 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
Author: jmort253,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-01-23 07:46:38

    <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. 'obiekt kotwicy' posiada własne właściwości * (dziedziczone)* do ustawiania odnośnika, jego tekstu. Więc po prostu ich używaj. .setAttribute jest bardziej ogólny, ale zwykle go nie potrzebujesz. a.title ="Blah" zrobi to samo i jest bardziej jasne! Sytuacja, która będzie wymagała .setAttribute jest to: var myAttrib = "title"; a.setAttribute( myAttrib , "Blah")

  2. Zostaw protokół otwarty. Zamiast http://example.com/path rozważ użycie //example.com/path. Sprawdź, czy example.com mogą być dostępne przez http: , jak również https:, ale 95% stron będzie działać na obu.

  3. OffTopic: to nie ma znaczenia przy tworzeniu linków w JS ale może dobrze wiedzieć: Cóż, czasami, jak w chromes dev-console, możesz użyć $("body") zamiast document.querySelector("body")a _$ = document.querySelector 'uszanuje' twoje wysiłki błędem nielegalnego wywołania przy pierwszym użyciu. To dlatego, że zadanie po prostu "łapie" .querySelector (ref do metody klasy). Z .bind(... będziesz również uwzględniać kontekst (tutaj jest to document) i otrzymasz metodę object, która będzie działać tak, jak możesz się tego spodziewać.

 1
Author: Nadu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-01 17:29:27

Wklejasz to w środku:

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

 -4
Author: zerodunwash,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-24 18:11:58