简体   繁体   English

将链接元素<a>添加到段落<p> Javascript

[英]Add Link Element <a> to paragraph <p> Javascript

I am trying to add a link into a paragraph that already has some text in it, but when I try this is just adds the text of the link element and not actual link. 我试图在已经包含一些文本的段落中添加一个链接,但是当我尝试这只是添加链接元素的文本而不是实际链接。 href or <a> tag. href或<a>标签。 Here is html 这是html

<div id="main_div"></div>

And here is Javascript 这是Javascript

var temp_link = document.createElement("A");
temp_link.href = "http://test.com";
temp_link.target = '_blank';

var par = document.createElement("P");
par.innerHTML = "some text: " + temp_link;

<!--I have also tried this line below -->
<!--    par.insertAdjacentHTML('beforeend', '<div><a>' + url +'</a></div>' -->);

document.getElementById("main_div").appendChild(par);

I have tried two things what is in the above javascript both what it would currently run and the line that is commented out, neither attach the link, they just add the text I have included JSFiddle . 我已经尝试了上面的javascript中的两个东西,无论它当前运行的是什么以及被注释掉的行,都没有附加链接,它们只是添加了我已经包含JSFiddle的文本。

How can I add it so that <a> links? 如何添加它以便<a>链接?

You can not mix innerHTML and createElement. 你不能混合innerHTML和createElement。 You need to append the element to the paragraph. 您需要将元素追加到段落中。

 var temp_link = document.createElement("a"); temp_link.href = "http://test.com"; temp_link.target = '_blank'; temp_link.innerHTML = "link"; var par = document.createElement("p"); par.innerHTML = "some text: "; par.appendChild(temp_link); document.getElementById("main_div").appendChild(par); 
 <div id="main_div"></div> 

or 要么

 var temp_link = document.createElement("a"); temp_link.href = "http://test.com"; temp_link.target = '_blank'; temp_link.innerHTML = "link"; var text = document.createTextNode("some text: "); var par = document.createElement("p"); par.appendChild(text); par.appendChild(temp_link); document.getElementById("main_div").appendChild(par); 
 <div id="main_div"></div> 

use innerHTML for the link name and outerhtml to get the full html of a elelmt 使用innerHTML作为链接名称和outerhtml来获取elelmt的完整html

var temp_link = document.createElement("A");    
temp_link.href = "http://test.com";
temp_link.target = '_blank';
temp_link.innerHTML ='click here';

var par = document.createElement("P");
par.innerHTML = "some text: " + temp_link.outerHTML;     

document.getElementById("main_div").appendChild(par);

Something like this should get you started: 这样的事情应该让你开始:

 var $p = $("<p>").text("some text:"); $p.append( $("<a>").attr("href", "http://test.com") .attr("target", "_blank") .text("click me") ); $("#main_div").append( $p); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="main_div"></div> 

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM