How to add a list of hyperlinks (with their events and properties) dynamically to a开发者_开发知识库 div in Javascript?
here's a pure Javascript alternative:
var mydiv = document.getElementById("myDiv");
var aTag = document.createElement('a');
aTag.setAttribute('href',"yourlink.htm");
aTag.innerText = "link text";
mydiv.appendChild(aTag);
I recommend that you use jQuery for this, as it makes the process much easier. Here are some examples using jQuery:
$("div#id").append('<a href="' + url + '">' + text + '</a>');
If you need a list though, as in a <ul>
, you can do this:
$("div#id").append('<ul>');
var ul = $("div#id > ul");
ul.append('<li><a href="' + url + '">' + text + '</a></li>');
var newA = document.createElement('a');
newA.setAttribute('href',"http://localhost");
newA.innerHTML = "link text";
document.appendChild(newA);
<script type="text/javascript" language="javascript">
function createDiv()
{
var divTag = document.createElement("div");
divTag.innerHTML = "Div tag created using Javascript DOM dynamically";
document.body.appendChild(divTag);
}
</script>
One more variation wrapped up nicely where setAttribute isn't needed.
There are 3 lines that wouldn't be needed if Wetfox could dry off.
var saveAs = function (filename, content) {
if(filename === undefined) filename = "Unknown.txt";
if(content === undefined) content = "Empty?!";
let link = document.createElement('a');
link.style.display = "none"; // because Firefox sux
document.body.appendChild(link); // because Firefox sux
link.href = "data:application/octet-stream," + encodeURIComponent(content);
link.download = filename;
link.click();
document.body.removeChild(link); // because Firefox sux
};
Thanks for the help.
With jquery
$("div#id").append('<a href=#>Your LINK TITLE</a>')
With javascript
var new_a = document.createElement('a');
new_a.setAttribute("href", "link url here");
new_a.innerHTML = "your link text";
//add new link to the DOM
document.appendChild(new_a);
var a = document.createElement('a');
a.target = '_blank';
a.href = '/solution_code/ + solution_code.id'
a.innerText = "Soution Code";
var container = document.getElementById('solution-code');
container.appendChild(a);
container.appendChild(document.createElement('br'));
精彩评论