简体   繁体   English

如何在Javascript中动态地将锚标记添加到div?

[英]How to add anchor tags dynamically to a div in Javascript?

如何在 Javascript 中将超链接列表(及其事件和属性)动态添加到 div?

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

I recommend that you use jQuery for this, as it makes the process much easier.我建议您为此使用jQuery ,因为它使过程更容易。 Here are some examples using jQuery:以下是一些使用 jQuery 的示例:

$("div#id").append('<a href="' + url + '">' + text + '</a>');

If you need a list though, as in a <ul> , you can do this:如果你需要一个列表,就像在<ul> ,你可以这样做:

$("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.另一个变体在不需要 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.谢谢您的帮助。

With jquery使用 jquery

  $("div#id").append('<a href=#>Your LINK TITLE</a>')

With javascript使用 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'));

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

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