Javascript 如何在Javascript中动态地将锚标记添加到div?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5519747/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add anchor tags dynamically to a div in Javascript?
提问by Ahmad Farid
How to add a list of hyperlinks (with their events and properties) dynamically to a div in Javascript?
如何在 Javascript 中将超链接列表(及其事件和属性)动态添加到 div?
回答by danniel
here's a pure Javascript alternative:
这是一个纯 Javascript 替代方案:
var mydiv = document.getElementById("myDiv");
var aTag = document.createElement('a');
aTag.setAttribute('href',"yourlink.htm");
aTag.innerText = "link text";
mydiv.appendChild(aTag);
回答by H?vard
I recommend that you use jQueryfor this, as it makes the process much easier. Here are some examples using jQuery:
我建议您为此使用jQuery,因为它使过程更容易。以下是一些使用 jQuery 的示例:
$("div#id").append('<a href="' + url + '">' + text + '</a>');
If you need a listthough, as in a <ul>
, you can do this:
如果你需要一个列表,就像在 a 中一样<ul>
,你可以这样做:
$("div#id").append('<ul>');
var ul = $("div#id > ul");
ul.append('<li><a href="' + url + '">' + text + '</a></li>');
回答by m4tt1mus
var newA = document.createElement('a');
newA.setAttribute('href',"http://localhost");
newA.innerHTML = "link text";
document.appendChild(newA);
回答by bensiu
<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>
回答by Master James
One more variation wrapped up nicely where setAttribute isn't needed.
另一个变体在不需要 setAttribute 的地方很好地结束了。
There are 3 lines that wouldn't be needed if Wetfox could dry off.
如果 Wetfox 可以变干,则不需要 3 条线。
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.
谢谢您的帮助。