setAttribute在Javascript中的var字符串

时间:2017-10-21 18:40:33

标签: javascript html

我想添加以下每个var一个链接字符串,并且在我的HTML中,我唯一拥有的是一个带ID集的简单div。



var home = "Home";
var news = "News";
var contact = "Contact";
var about = "About";
document.getElementById("myTopnav").innerHTML = home + " " + news + " " + contact + " " + about;

<div class="topnav" id="myTopnav">

</div>
&#13;
&#13;
&#13;

正如您所看到的那样,它是一个菜单,我只想使用JavaScript创建一个。

3 个答案:

答案 0 :(得分:2)

看起来你刚开始,所以我建议以可维护的方式开始。在列表中定义菜单项,而不是单个变量,然后单步执行并附加a标记。像这样:

var menuItems = [{
        name:"Home",
        link:"/home"
    },
    {
        name:"News",
        link:"/news"
    },
    {
        name:"Contact",
        link:"/contact"
    },
    {
        name:"About",
        link:"/about"
    }]
var menu = document.getElementById("myTopnav")
for(var i = 0; i < menuItems.length; i++) {
    var link = document.createElement('a');
    var linkText = document.createTextNode(menuItems[i].name);
    link.appendChild(linkText);
    link.href = menuItems[i].link;
    menu.appendChild(link);
}
#myTopnav a{
        margin-left: 10px
    }
<div class="topnav" id="myTopnav"></div>

答案 1 :(得分:1)

<div class="topnav" id="myTopnav"></div>

<script>
var links = [
  ['Home', '/'],
  ['News', '/news/'],
  ['Contact', '/contact/'],
  ['About', '/about/']
];

function makeNav( links ) {
  var nav = document.getElementById('myTopnav');
  for ( var i = 0; i < links.length; i++ ) {
    nav.innerHTML += '<a href="' + links[i][1] + '">' + links[i][0] + '</a>';
  }
  return nav;
}

makeNav( links );
</script>

答案 2 :(得分:0)

您可以将元素包装在html标记中,例如<a></a> or <li><a></a></li>

document.getElementById('myTopnav').innerHTML = '<a href="#">' + home + '</a>' + ...