如何从Array写入所有数据?

时间:2013-11-29 16:12:58

标签: javascript html

我喜欢HTML:

<div id="divid">
  <a href="d#link1">1</a>
    <a href="d#link2">2</a>
    <a href="d#link3">3</a>
    .....................
</div>

我有脚本从div获取所有链接:

<script>
    var links = document.getElementById('divid').getElementsByTagName('a') ;
</script>

然后我希望将链接写入类,如:

<script>
        var links = document.getElementById('divid').getElementsByTagName('a') ;
        document.write("<div class="'+link[1]+" "+ link[i]+'">Class is added links</div>");
</script>

这意味着写完后我有HTML:

<div class="d#link1 d#link2 d#link3">Classes is added links</div>

我该怎么做?是否使用for循环?如何?

2 个答案:

答案 0 :(得分:3)

您必须从每个元素获取href属性。把它们放在一个数组中,你就可以加入字符串了:

var elements = document.getElementById('divid').getElementsByTagName('a');
var links = [];
for (var i = 0; i < elements.length; i++) {
  links.push(elements[i].href);
}
document.write("<div class="' + links.join(" ") + '">Class is added links</div>");

答案 1 :(得分:1)

joinmap结合使用:

var classString = links.map(function(link) { return link.attributes.href; } ).join(' ');