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

spe*_*123 4 html javascript css jquery

我正在尝试将链接添加到已经有一些文本的段落中,但是当我尝试时,这只是添加了链接元素的文本而不是实际链接。href 或<a>标签。这是 html

<div id="main_div"></div>
Run Code Online (Sandbox Code Playgroud)

这是 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);
Run Code Online (Sandbox Code Playgroud)

我已经尝试了上面 javascript 中的两件事,包括当前运行的内容和注释掉的行,都没有附加链接,他们只是添加了我包含的文本JSFiddle

如何添加它以便<a>链接?

epa*_*llo 6

您不能混合使用innerHTML 和createElement。您需要将元素附加到段落中。

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);
Run Code Online (Sandbox Code Playgroud)
<div id="main_div"></div>
Run Code Online (Sandbox Code Playgroud)

或者

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);
Run Code Online (Sandbox Code Playgroud)
<div id="main_div"></div>
Run Code Online (Sandbox Code Playgroud)